Last active
May 18, 2019 01:15
-
-
Save domenic/7706162 to your computer and use it in GitHub Desktop.
Promise combinators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Promise.all = iterable => { | |
return new this((resolve, reject) => { | |
const values = []; | |
let countdown = 0; | |
let index = 0; | |
for (let nextValue of iterable) { | |
const nextPromise = this.resolve(nextValue); | |
const countdownFunction = makeCountdownFunction(index); | |
nextPromise.then(countdownFunction, reject); | |
++index; | |
++countdown; | |
} | |
function makeCountdownFunction(index) { | |
return value => { | |
values[index] = value; | |
if (--countdown === 0) { | |
resolve(values); | |
} | |
}; | |
} | |
}); | |
}; | |
Promise.race = iterable => { | |
return new this((resolve, reject) => { | |
for (let nextValue of iterable) { | |
let nextPromise = this.resolve(nextValue); | |
nextPromise.then(resolve, reject); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I doubt
this
inside arrow functions is the correct implementation here.