Skip to content

Instantly share code, notes, and snippets.

@lackneets
Created February 5, 2021 07:03
Show Gist options
  • Save lackneets/f0fc431693ef14c63ac35c91ae167d58 to your computer and use it in GitHub Desktop.
Save lackneets/f0fc431693ef14c63ac35c91ae167d58 to your computer and use it in GitHub Desktop.
Promise One by One
(() => {
var p1 = (val) => new Promise((resolve, reject) => {
console.log('sent process 1')
setTimeout((val) => {
console.log('done1')
resolve(val)
}, 100, 'one');
});
var p2 = (val) => new Promise((resolve, reject) => {
console.log('sent process 2')
setTimeout((val) => {
console.log('done2')
resolve(val)
}, 200, 'two');
});
var p3 = (val) => new Promise((resolve, reject) => {
console.log('sent process 3')
setTimeout((val) => {
console.log('done3')
resolve(val)
}, 300, 'three');
});
var p4 = (val) => new Promise((resolve, reject) => {
console.log('sent process 4')
setTimeout((val) => {
console.log('done4')
resolve(val)
}, 400, 'four');
});
// var p5 = (val) => new Promise((resolve, reject) => {
// console.log('sent process 5')
// reject('reject');
// });
[p1, p2, p3, p4].reduce((promise, task) => promise.then(async processRes => processRes.concat(await task())), Promise.resolve([])).then((allRes) => {
console.log('done~~~~', allRes)
})
// Promise.all([p1, p2, p3, p4, p5]).then(values => {
// console.log(values);
// }, reason => {
// console.log(reason)
// });
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment