异步/等待分配给对象键:它是并发的吗? [英] Async / await assignment to object keys: is it concurrent?
问题描述
我知道这样做:
const resultA = await a()
const resultB = await b()
// code here
有效
a().then( resultA => {
b().then( resultB => {
// code here
})
})
基本上,a()运行然后 b()运行.我嵌套它们以显示resultA和resultB都在我们的范围内;但是两个功能都没有一次运行.
Basically, a() runs then b() runs. I nested them to show that both resultA and resultB are in our scope; yet both function didn't run at once.
那呢:
const obj = {
result1: await a(),
result2: await b()
}
a()和b()是否同时运行?
do a() and b() run concurrently?
供参考:
const asyncFunc = async (func) => await func.call()
const results = [funcA,funcB].map( asyncFunc )
我知道这里funcA
和funcB
确实可以同时运行.
I know here funcA
and funcB
do run concurrently.
奖金:
您如何表示对象分配
const obj = {
result1: await a(),
result2: await b()
}
使用then
/回调?
更新:
@Bergi在这个答案中是正确的,这是顺序发生的.为了共享一个不错的解决方案,同时使一个对象同时完成这项工作,而不必从一个数组中分解该对象,也可以如下使用Bluebird
@Bergi is correct in this answer, this occurs sequentially. To share a nice solution for having this work concurrently for an object without having to piece together the object from an array, one can also use Bluebird
as follows
const obj2 = Bluebird.props(obj)
http://bluebirdjs.com/docs/api/promise.props.html
推荐答案
不,每个await
都将停止执行,直到诺言已经兑现,甚至是中间表达为止.它们是否碰巧是同一条语句的一部分都没关系.
No, every await
will stop the execution until the promise has fulfilled, even mid-expression. It doesn't matter whether they happen to be part of the same statement or not.
如果要并行运行它们,并且仅等待一次结果,则必须使用await Promise.all(…)
.就您而言,您会写
If you want to run them in parallel, and wait only once for their result, you have to use await Promise.all(…)
. In your case you'd write
const [result1, result2] = await Promise.all([a(), b()]);
const obj = {result1, result2};
您如何使用
then
/回调表示对象分配?
How would you represent the object assignment using
then
/ callbacks?
每个等待的值都有临时变量.每个await
都转换为一个then
调用:
With temporary variables for each awaited value. Every await
translates into one then
call:
a().then(tmp1 => {
return b().then(tmp2 => {
const obj = {
result1: tmp1,
result2: tmp2
};
return …
});
})
如果想做修脚,我们必须将对象的创建分开:
If we wanted to be pedantic, we'd have to pick apart the object creation:
const tmp0 = {};
a().then(tmp1 => {
tmp0.result1 = tmp1;
return b().then(tmp2 => {
tmp0.result2 = tmp2;
const obj = tmp0;
return …
});
})
这篇关于异步/等待分配给对象键:它是并发的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!