javascript - Parallel vs Series - 如何使用异步按顺序执行函数
问题描述
根据 google docs 对 Async 的解释,以下名为“parallel”的函数应并行执行,而名为“series”的函数应按顺序执行。
Google Developers 上的异步函数说明
并行应该需要 2 秒才能完成。
系列应该需要 4 秒。
但是,它们都在 2 秒内完成。
为什么 series() 总共不需要 4 秒?我期待第一个计时器在 2 秒后完成,然后第二个计时器在 2 秒后完成?
async function series() {
function timer(time) { setTimeout(function(){ console.log(`Hello ${time}`) }, time); }
await timer(2000); // Wait 2 seconds…
await timer(2000); // …should wait another 2 seconds
}
series() // should take 4 seconds to complete, but only takes 2 seconds
为什么这可以并行工作,但系列不能串联工作?
async function parallel() {
function timer(time) { setTimeout(function(){ console.log(`Hello ${time}`) }, time); }
let one = timer(2000); // Start a 2 second timer asynchronously…
let two = timer(2000); // …meaning this timer happens in parallel.
await one; // Wait 2 seconds for the first timer
await two; // …by which time this time finishes around same time
}
parallel() // completes in 2 seconds
解决方案
推荐阅读
- c# - how to display MLM data in treeview in asp.net
- javascript - 来自 API 的数据呈现为空(数组/对象问题)
- scala - Split one row into multiple rows of dataframe
- javascript - How do I (correctly) check whether an element is within the viewport in React?
- uml - UML 类 - 当没有派生类时使用基类
- php - Is it possible to tell Composer not to uninstall already installed dependencies when using the composer command?
- python - I read image file as binary strange symbols appear
- javascript - 从单位表示(rem/vh/px/...)计算(javascript)像素的最佳方法
- c# - 微服务收不到 RabbitMq 消息
- spring-boot - 尝试从 Docker 访问 ES 实例时出现 SSLHandshakeException