Last active
August 2, 2019 01:26
-
-
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 ?
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
// 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wow so many promises