`await` 什么时候同时解析?

When is `await` resolved simultaneously?

async function 的 MDN 文档目前给出了以下两种使用方式的组合示例 await。为了强调,我重新排序了一点:

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}


async function add1(x) {
  const a = await resolveAfter2Seconds(20);
  const b = await resolveAfter2Seconds(30);
  return x + a + b;
}

async function add2(x) {
  const p_a = resolveAfter2Seconds(20);
  const p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
}


add1(10).then(v => {
  console.log(v);  // prints 60 after 4 seconds.
});

add2(10).then(v => {
  console.log(v);  // prints 60 after 2 seconds.
});

这让我有点惊讶。为什么

const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;

依次解决两个承诺,而

return x + await p_a + await p_b;

似乎同时解决了两个承诺?这种行为是专门为 await 指定的,还是其他原因的自然结果?

async function add2(x) {
  const p_a = resolveAfter2Seconds(20);
  const p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
}

在此语句中,p_a 和 p_b 是并行启动的(即,一旦您生成承诺),因此当您等待 p_a 和 p_b它们看起来是平行的,而不是顺序的。

要获得其他功能(等待系列),您需要:

return x + await resolveAfter2Seconds(20) + await resolveAfter2Seconds(30);