【问题标题】:Javascript Async / Await get tasks done and finally do something else [duplicate]Javascript Async / Await 完成任务,最后做其他事情[重复]
【发布时间】:2018-12-06 21:56:23
【问题描述】:

我需要让一堆函数完成一些任务,并在最终函数中对结果做一些事情。

我在考虑使用异步/等待?

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 / Await 来做到这一点。

【问题讨论】:

  • 绝对在final中使用Promise.all

标签: javascript promise ecmascript-2017


【解决方案1】:

请记住,当您声明一个函数async 时,真正发生在幕后的是该函数将返回一个Promise,而函数的返回值将是@987654323 的值@ 解析为。

由于函数返回Promise,您可以使用该事实来链接调用。

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

dosomething().then(dosomethingelse).then(final)

如果你想并行执行dosomethingdosomethingelse,等待两者都完成,然后才执行final,你可以这样做:

Promise.all([dosomething(), dosomethingelse()]).then(final)

这只是一个承诺,仅此而已。要详细了解您可以做什么,最好的办法可能是深入研究 Promise。

对于 CS 理论的学生和爱好者来说,学习 Monads 也可以是一个不错的选择 - 它是一个 Monad,promise 上的操作可以看作是 monadic 操作。

【讨论】:

  • 你能在地图上使用 Promise.all,例如 Promise.all(list.map(e => e.runslowly())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 2015-04-09
  • 1970-01-01
相关资源
最近更新 更多