如何异步编程(承诺)JavaScript实现?是不是JavaScript的一个UI线程环境中? [英] how is async programming (promises) implemented in javascript? isn't javascript a ui-threaded environment?

查看:112
本文介绍了如何异步编程(承诺)JavaScript实现?是不是JavaScript的一个UI线程环境中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JS承诺允许你这样做异步编程,如下:

  DoSomething的(),然后(成功,失败)。DoSomethingElse();

每当我写的previous code达到 DoSomethingElse()到达之前成功
这怎么可能?是不是JS单线程环境(不包括网络工作人员)?它是用的setTimeout 做了什么?


解决方案

是,JavaScript是单线程的,这意味着你永远不应该阻止该单个线程。任何长期运行,等待操作(通常是AJAX调用或休眠/暂停)使用回调来实现。

不看这里的实现是会发生什么:


  1. 的DoSomething 被调用,它接收成功失败函数作为参数。<​​/ p>


  2. 它做什么它需要做的(可能引发长期运行的AJAX调用),并返回


  3. DoSomethingElse()被称为


  4. ...


  5. 一段时间后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:

  1. DoSomething is called and it receives success and failure functions as arguments.

  2. It does what it needs to do (probably initiating long-running AJAX call) and returns

  3. DoSomethingElse() is called

  4. ...

  5. Some time later AJAX response arrives. It calls previously defined success and failure function

See also (similar problems)

这篇关于如何异步编程(承诺)JavaScript实现?是不是JavaScript的一个UI线程环境中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆