We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
今天写代码碰到一个场景,有多个异步任务,且异步任务需要顺序执行(执行完一个之后执行下一个)。 最后异步任务写成 promise 之后都放在了一个数组里,需求是让数组里的 promise 顺序处理。代码如下
var arr = [ () => new Promise(resolve => setTimeout(() => { console.log('p1 done'); resolve(); }, 3000)), () => new Promise(resolve => setTimeout(() => { console.log('p2 done'); resolve(); }, 2000)), () => new Promise(resolve => setTimeout(() => { console.log('p3 done'); resolve(); }, 1000)), ];
怎么实现,让这个数组里的 promise 顺序执行?即打印出 ->->-> p1 done ->-> p2 done -> p3 done
->->-> p1 done ->-> p2 done -> p3 done
The text was updated successfully, but these errors were encountered:
使用 reduce ~
arr.reduce((prev, cur) => { var p = prev().then(() => cur()); return () => p; });
Sorry, something went wrong.
arr.reduce((prev, cur) => { return prev.then(cur); }, Promise.resolve()).then();
@miSunLaughing 用 async/await 也太狡猾了,哈哈
@sunhengzhe 哈哈,我把格式调下把代码贴出来吧
// 使用async函数 async function chainAsync(arr) { var ret = null; try { for(var item of arr) { ret = await item(); } } catch(e) { /* 忽略错误,继续执行 */ } return ret; }
No branches or pull requests
今天写代码碰到一个场景,有多个异步任务,且异步任务需要顺序执行(执行完一个之后执行下一个)。
最后异步任务写成 promise 之后都放在了一个数组里,需求是让数组里的 promise 顺序处理。代码如下
怎么实现,让这个数组里的 promise 顺序执行?即打印出
->->-> p1 done ->-> p2 done -> p3 done
The text was updated successfully, but these errors were encountered: