我知道这样做:
const resultA = await a()
const resultB = await b()
// code here
有效地
a().then( resultA => {
b().then( resultB => {
// code here
})
})
基本上,a() 运行然后b() 运行。我嵌套它们以表明 resultA 和 resultB 都在我们的范围内;但是这两个功能都没有立即运行。
但是这个呢:
const obj = {
result1: await a(),
result2: await b()
}
a() 和 b() 是否同时运行?
以供参考:
const asyncFunc = async (func) => await func.call()
const results = [funcA,funcB].map( asyncFunc )
我知道这里funcA
并funcB
同时运行。
奖金:
您将如何表示对象分配
const obj = {
result1: await a(),
result2: await b()
}
使用then
/ 回调?
更新:
@Bergi 在这个答案中是正确的,这是按顺序发生的。为了共享一个很好的解决方案,让一个对象同时进行这项工作,而不必将数组中的对象拼凑在一起,也可以使用Bluebird
如下
const obj2 = Bluebird.props(obj)