并行与串行异步代码(异步和等待)

时间:2017-12-22 06:34:15

标签: javascript asynchronous

我正在阅读有关异步代码的更多内容 - 在Google的这个https://developers.google.com/web/fundamentals/primers/async-functions中,我意识到如果我添加等待代码的每一行,由于代码在系列中运行,有时需要更长时间才能处理而不是平行。

这是该页面上提供的2个代码示例。

async function series() {
  await wait(500); // Wait 500ms…
  await wait(500); // …then wait another 500ms.
  return "done!";
}


async function parallel() {
  const wait1 = wait(500); // Start a 500ms timer asynchronously…
  const wait2 = wait(500); // …meaning this timer happens in parallel.
  await wait1; // Wait 500ms for the first timer…
  await wait2; // …by which time this timer has already finished.
  return "done!";
}

我可以理解,因为两个代码看起来都相似,就像他们在函数awaitwait1上使用wait 2一样。是什么让一个人平行而另一个人串联?

2 个答案:

答案 0 :(得分:0)

series()可能较慢的原因是因为您正在关闭等待它返回的第一个async调用,而当发生这种情况时,您的方法会在此时被阻止。一旦async调用返回,您的下一个async调用将被执行,您将阻止您的方法并等待该调用的结果。

'Parallel'可能会更快,因为您同时关闭了asyncawait来电,然后再parallel()这两个来电。所以在async中,你基本上是在同一时间开始执行RemoveFromCache方法(wait1和wait2)。

答案 1 :(得分:-2)

你可能知道JS是Asynchnorous。这意味着当函数被执行时,JS不会等到它完成,然后再转到下一行代码。这有时是令人沮丧的原因。

说完了......再看看这个功能:

 const wait1 = wait(500); // wait() is executed & JS Moves on i.e. no waiting
  const wait2 = wait(500); //wait() is executed again & JS moves on again.

  await wait1; // wait(500) has been execueting, so we just have wait for it to finish
  await wait2; // 2nd wait(500) also has been excueting so we just have to wait for it to finish.

结果,这些功能已经并行执行并且将具有比第一示例更好的性能,因为第一示例中的功能顺序执行。在第二个例子中,它们并行执行,但我们只是强制JS按照我们需要的顺序返回函数的结果。

以下是另一种观察方式:

顺序等待

Example:

var result1 = await wait1(2);
var result2 = await wait2(result1);
var result3 = await wait3(result2);

等待Asynchnorously

Example:

var results = await Promise.all([wait1(1), wait2(2)]);