JavaScript Promise 是异步的吗? [英] Are JavaScript Promise asynchronous?

查看:27
本文介绍了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?

例如,我有一个函数将函数 f 与参数数组 args 包装在 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,只依赖浏览器支持的 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;事实上,这是 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

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

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天全站免登陆