异步执行某事是否与将其推到调用堆栈的后面一样?
Is executing something asynchronously the same as pushing it to the back of the call stack?
"When there's nothing to do, check the queue. But only check the queue
when there's nothing left to do."
~ Javascript (https://www.youtube.com/watch?v=vMfg0xGjcOI)
所以据我了解,这基本上意味着你在延迟执行。像
SomeAsynchronousFunction();
SomeRegularFunction();
SomeOtherRegularFunction();
只是意味着您实际上是在将任务重新安排到
SomeRegularFunction();
SomeOtherRegularFunction();
SomeAsynchronousFunction();
三个函数的主体是如何执行的。除此之外,如果你的 browser/hardware 支持并行计算,如果 SomeAsynchronousFunction
的主体对其他两个函数没有任何依赖,那么它将与其他两个函数并行执行。那正确吗?还是我完全糊涂了?
你很接近。但通常会有 SomeAsynchronousFunction
的某些部分是同步的,这些部分将立即执行——只有函数的完成才是异步的。例如,它可能执行一个 AJAX 调用,因此它首先创建 XHR 对象,将参数收集到一个 FormData
对象中,然后立即调用 xhr.send()
;异步部分是 onreadystatechange
回调函数的执行,它发生在服务器响应并且事件处理循环无事可做时。所以实际的执行顺序是这样的:
synchronous parts of SomeAsynchronousFunction();
SomeRegularFunction();
SomeOtherRegularFunction();
callback function from SomeAsynchronousFunction();
Javascript 运行s 在单个线程上,是非阻塞的并使用所谓的事件循环,因此您的函数 运行 按原始顺序排列,但异步调用,当他们 return 将另一条消息添加到事件循环并在事件循环中处理完所有其他前面的消息时执行。有关详细信息,我建议阅读来自 Mozilla 开发人员网络的这篇文章,Concurrency model and Event Loop
"When there's nothing to do, check the queue. But only check the queue when there's nothing left to do."
~ Javascript (https://www.youtube.com/watch?v=vMfg0xGjcOI)
所以据我了解,这基本上意味着你在延迟执行。像
SomeAsynchronousFunction();
SomeRegularFunction();
SomeOtherRegularFunction();
只是意味着您实际上是在将任务重新安排到
SomeRegularFunction();
SomeOtherRegularFunction();
SomeAsynchronousFunction();
三个函数的主体是如何执行的。除此之外,如果你的 browser/hardware 支持并行计算,如果 SomeAsynchronousFunction
的主体对其他两个函数没有任何依赖,那么它将与其他两个函数并行执行。那正确吗?还是我完全糊涂了?
你很接近。但通常会有 SomeAsynchronousFunction
的某些部分是同步的,这些部分将立即执行——只有函数的完成才是异步的。例如,它可能执行一个 AJAX 调用,因此它首先创建 XHR 对象,将参数收集到一个 FormData
对象中,然后立即调用 xhr.send()
;异步部分是 onreadystatechange
回调函数的执行,它发生在服务器响应并且事件处理循环无事可做时。所以实际的执行顺序是这样的:
synchronous parts of SomeAsynchronousFunction();
SomeRegularFunction();
SomeOtherRegularFunction();
callback function from SomeAsynchronousFunction();
Javascript 运行s 在单个线程上,是非阻塞的并使用所谓的事件循环,因此您的函数 运行 按原始顺序排列,但异步调用,当他们 return 将另一条消息添加到事件循环并在事件循环中处理完所有其他前面的消息时执行。有关详细信息,我建议阅读来自 Mozilla 开发人员网络的这篇文章,Concurrency model and Event Loop