我正在阅读有关异步代码的更多内容 - 在本文 https://developers.google.com/web/fundamentals/primers/async-functions 中通过Google,我意识到,如果我在每一行代码中添加await,有时由于代码以串行方式而不是并行方式运行,处理时间会更长。
这是该页面上提供的 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!";
}
我可以理解吗,因为这两个代码看起来很相似,因为它们在函数 wait1
和 wait 2
上使用了 await
。是什么使一个并联而另一个串联?
最佳答案
series()
可能较慢的原因是您正在触发第一个 async
调用等待它返回,而此时您的方法被阻止在那时候。一旦该async
调用返回,您将执行下一个async
调用,您也将阻塞您的方法并等待该调用的结果。
“并行”
可能会更快,因为您几乎同时触发了两个 async
调用,然后您等待
这两个调用。因此,在parallel()中,您基本上是同时开始异步方法执行(wait1和wait2)。
关于javascript - 并行与串行中的异步代码(异步和等待),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936886/