问题描述
在JS承诺允许你这样做异步编程,如下:
DoSomething的(),然后(成功,失败)。DoSomethingElse();
每当我写的previous code达到 DoSomethingElse()
到达之前成功
。
这怎么可能?是不是JS单线程环境(不包括网络工作人员)?它是用的setTimeout
做了什么?
是,JavaScript是单线程的,这意味着你永远不应该阻止该单个线程。任何长期运行,等待操作(通常是AJAX调用或休眠/暂停)使用回调来实现。
不看这里的实现是会发生什么:
-
的DoSomething
被调用,它接收成功
和失败
函数作为参数。 -
它做什么它需要做的(可能引发长期运行的AJAX调用),并返回
-
DoSomethingElse()
被称为 -
...
-
一段时间后AJAX响应到达。它调用previously定义
成功
和失败
函数
参见(类似问题)
Promises in JS allow you to do async programming, as follows:
DoSomething().then(success, failure);
DoSomethingElse();
whenever i write the previous code it reaches DoSomethingElse()
before it reaches success
.How is that possible? Isn't JS a single threaded environment (not including web-workers)? is it done with setTimeout
?
Yes, JavaScript is single-threaded, which means you should never block this single thread. Any long-running, waiting operation (typically AJAX calls or sleeps/pauses) are implemented using callbacks.
Without looking at the implementation here is what happens:
DoSomething
is called and it receivessuccess
andfailure
functions as arguments.It does what it needs to do (probably initiating long-running AJAX call) and returns
DoSomethingElse()
is called...
Some time later AJAX response arrives. It calls previously defined
success
andfailure
function
See also (similar problems)
- JavaScript equivalent of SwingUtilities.invokeLater()
- Are there any atomic javascript operations to deal with Ajax's asynchronous nature?
- jqGrid custom edit rule function using Ajax displays "Custom Function should return array!"
这篇关于如何异步编程(承诺)JavaScript实现?是不是JavaScript的一个UI线程环境中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!