JavaScript Promise是否异步? [英] Are JavaScript Promise asynchronous?

查看:79
本文介绍了JavaScript Promise是否异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简短的澄清问题:JavaScript Promise是异步的吗?我已经阅读了很多关于Promise和异步编程(即ajax请求)的文章.如果Promise不是异步的,我们如何做到呢?

Just a quick question of clarifications: is JavaScript Promise asynchronous? I've been reading a lot of posts on Promise and async programming (namely ajax requests). If Promise is not async, how do we make it so?

例如,我有一个函数可以将带有参数数组args的函数f包装在Promise中.本质上,关于f的所有内容都不是异步的.

For example, I have a function to wrap a function f with argument array args inside a Promise. Nothing about f inherently is async.

function getPromise(f, args) {
 return new Promise(function(resolve, reject) {
  var result = f.apply(undefined, args);
  resolve(result);
 });
}

为了使这个异步,我读了一些SO帖子,并决定setTimeout是很多人建议使代码不阻塞的东西.

To make this async, I read some SO posts and decided that the setTimeout is what a lot of people were recommending to make code non-blocking.

function getPromise(f, args) {
 return new Promise(function(resolve, reject) {
  setTimeout(function() { 
   var r = f.apply(undefined, args);
   resolve(r);
  }, 0);
 });
}

这种使用setTimeout的方法是否可以使代码在Promise内部无阻塞?

Would this approach with setTimeout work to make code non-blocking inside a Promise?

(请注意,我不依赖任何第三方Promise API,只是浏览器支持的东西).

(Note that I am not relying on any third-party Promise API, just what is supported by the browsers).

推荐答案

我认为您正在误解. JavaScript代码被 始终*阻止 ;那是因为它在单个线程上运行. Javascript异步编码风格的优点在于,诸如I/O之类的外部操作不需要阻塞该线程.尽管处理I/O响应的回调仍处于阻塞状态,并且其他JavaScript无法同时运行.

I think you are working under a misunderstanding. JavaScript code is always* blocking; that is because it runs on a single thread. The advantages of the asynchronous style of coding in Javascript is that external operations like I/O do not require blocking that thread. The callback that processes the response from the I/O is still blocking though and no other JavaScript can run concurrently.

*除非您考虑运行多个进程(或在浏览器上下文中运行WebWorkers).

* Unless you consider running multiple processes (or WebWorkers in a browser context).

现在针对您的具体问题:

Now for your specific questions:

一个简短的澄清问题:JavaScript Promise是异步的吗?

Just a quick question of clarifications: is JavaScript Promise asynchronous?

否,传递到Promise构造函数中的回调是立即并同步执行的,尽管绝对有可能启动异步任务(例如超时或写入文件),然后等待该异步任务完成后再解决承诺;实际上,这是Promise的主要用例.

No, the callback passed into the Promise constructor is executed immediately and synchronously, though it is definitely possible to start an asynchronous task, such as a timeout or writing to a file and wait until that asynchronous task has completed before resolving the promise; in fact that is the primary use-case of promises.

这种使用setTimeout的方法是否可以使代码在Promise中无阻塞?

Would this approach with setTimeout work to make code non-blocking inside a Promise?

否,它所做的只是更改执行顺序.脚本的其余部分将一直执行到完成为止,然后再无其他操作时,将执行setTimeout的回调.

No, all it does is change the order of execution. The rest of your script will execute until completion and then when there is nothing more for it to do the callback for setTimeout will be executed.

为澄清起见:

console.log( 'a' );

new Promise( function ( ) {
    console.log( 'b' );
    setTimeout( function ( ) {
        console.log( 'D' );
    }, 0 );
} );

// Other synchronous stuff, that possibly takes a very long time to process

console.log( 'c' );

上面的程序确定性地打印:

The above program deterministically prints:

a
b
c
D

这是因为直到主线程无事可做(在记录"c"之后),才会执行setTimeout的回调.

That is because the callback for the setTimeout won't execute until the main thread has nothing left to do (after logging 'c').

这篇关于JavaScript Promise是否异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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