Async / await assignment to object keys: is it concurrent?

泪湿孤枕 提交于 2019-11-29 14:06:17

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.

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};

How would you represent the object assignment using then / callbacks?

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 …
  });
})

do a() and b() run concurrently?

No, they run sequentially.

The equivalent would be something like

a()
.then(result1 => b())
  .then(result2 => ({result1, result2}))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!