Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active May 18, 2019 01:15
Show Gist options
  • Save domenic/7706162 to your computer and use it in GitHub Desktop.
Save domenic/7706162 to your computer and use it in GitHub Desktop.
Promise combinators
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);
}
});
};
@Ltrlg
Copy link

Ltrlg commented Oct 3, 2016

I doubt this inside arrow functions is the correct implementation here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment