Skip to content

Instantly share code, notes, and snippets.

@JackyYin
Last active August 2, 2019 01:26
Show Gist options
  • Save JackyYin/e667e6f4bade95a46258397eccc20564 to your computer and use it in GitHub Desktop.
Save JackyYin/e667e6f4bade95a46258397eccc20564 to your computer and use it in GitHub Desktop.
Imagine we have an array of 10000 promises, how do we process them one by one ?
// Imagine we have an array of 10000 promises,
// How do we process them one by one ?
// Here is a general version g and a recursive version r
let input = [];
for (let i = 1; i <= 10000; i++) {
input.push(Promise.resolve(i));
}
const g = arr => arr.reduce((p, pnext) => p.then(v => {
console.log(v);
return pnext;
}), Promise.resolve(0));
const r = arr => {
if (arr.length === 1) return arr[0];
return arr[0].then(v => {
console.log(v);
return r(arr.slice(1))
});
}
g(input).then(val => {
console.log(val);
});
r(input).then(val => {
console.log(val);
});
@dontw
Copy link

dontw commented Aug 2, 2019

wow so many promises

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