何时“等待”同时解决?

时间:2017-10-31 23:39:55

标签: javascript async-await es2017

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指定的,还是其他东西的自然结果?

1 个答案:

答案 0 :(得分:7)

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