何时同时解决“等待”



异步函数的 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 是并行启动的(即,一旦您生成 promise),因此当您等待 p_a 并p_b时,它们将显示为并行的,而不是顺序的。

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

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

最新更新