Javascript异步/等待完成任务并最终执行其他操作

Javascript异步/等待完成任务并最终执行其他操作,javascript,promise,ecmascript-2017,Javascript,Promise,Ecmascript 2017,我需要一组函数来完成一些任务,并在最终的函数中对结果做一些处理 我在考虑使用async/await async function dosomething() { // do stuff // await till finished then grab the result } async function dosomethingelse() { // do stuff // await till finished then grab the result }

我需要一组函数来完成一些任务,并在最终的函数中对结果做一些处理

我在考虑使用async/await

async function dosomething() {
    // do stuff
    // await till finished then grab the result 
}

async function dosomethingelse() {
    // do stuff
    // await till finished then grab the result 
}

function final() {
    if (dosomething_result) {
     // do something
    }

    etc...
}
所以基本上,
final()
在dosomething和dosomethingelse完成之前不会运行

我希望我已经解释清楚了


我的问题是…如果Async/Wait是实现这一点的方法,我该如何使用它。

请记住,当您声明函数
Async
时,真正发生在幕后的是函数将返回一个
承诺,函数的返回值将是
Promise
解析为的值

由于函数返回一个
承诺
,因此可以使用该事实来链接调用

例如,如果您想要完全顺序执行,您可以:

dosomething().then(dosomethingelse).then(final)
如果要并行执行
dosomething
dosomethingelse
,请等待两者完成,然后执行
final
,您可以执行以下操作:

Promise.all([dosomething(), dosomethingelse()]).then(final)
这只是一个承诺,仅此而已。要想了解更多关于你能做什么的信息,最好的办法可能是深入了解承诺


对于CS理论的学生和爱好者来说,学习单子也可以是一个不错的额外任务——它是一个单子,承诺上的操作可以被视为一元操作。

一定要使用
Promise.all
final
中可以使用Promise.all在地图上,例如Promise.all(list.map(e=>e.runslowly())