简体   繁体   English

包含for循环的基于Promise的函数不是异步运行的

[英]Promise-based function containing for-loop not running asynchronously

I have the following code: 我有以下代码:

function asyncLoop() {
    return new Promise(function(res, rej) {
        for(let i=0;i<=400000000;i++) {
            if(i===400000000) {console.log("done"); res();}
        }
    });
}

asyncLoop().then(()=>{console.log("then")});
console.log("out");

I am getting the following output: 我得到以下输出:

done
out
then

According to my understanding of Promises, the asyncLoop should have run asynchronously and the following should have been the output: 根据我对Promises的理解,asyncLoop应该是异步运行的,以下应该是输出:

out
done
then

What am I missing? 我错过了什么?

Your loop is inside the callback that you passed to new Promise . 你的循环在你传递给new Promise的回调中。 This function is called the 'executor': 这个函数叫做'executor':

function executor(resolve, reject)

The executor is called synchronously by new Promise . 执行程序由new Promise 同步调用。 The role of the executor is to set up any asynchronous events in order to have resolve or reject eventually called. 执行者的作用是设置任何异步事件,以便有resolvereject最终调用。

See MDN: Promise constructor parameters 请参阅MDN: Promise构造函数参数

This function is invoked immediately with the resolving functions as its two arguments. 使用解析函数作为其两个参数立即调用此函数。

The constructor will not return until the executor has completed 在执行程序完成之前,构造函数不会返回

You've made a wrong assumption. 你做了一个错误的假设。 Promises are not meant to be async, they are used in an async context to bring an easier way to handle the calls. Promise并不意味着异步,它们在异步上下文中使用,以便更轻松地处理调用。 To make a process "kind of async", you could use setTimeout() . 要使进程“有点异步”,可以使用setTimeout()

function asyncLoop() {
    return new Promise(function(res, rej) {
        setTimeout(function() {
            for(let i=0;i<=400000000;i++) {
                if(i===400000000) {console.log("done"); res();}
            }
        }, 0);
    });
}

asyncLoop().then(()=>{console.log("then")});
console.log("out");

A promise is just a return value one attaches callbacks to instead of passing callbacks into a function, a convention with several benefits. promise只是一个返回值,它附加回调而不是将回调传递给函数,这是一个有几个好处的约定。 See Using promises on MDN for more. 有关更多信息,请参阅在MDN上使用promises

JavaScript is single-threaded with an event loop. JavaScript是单线程的,带有事件循环。 .then and setTimeout schedule events. .thensetTimeout安排事件。

All JavaScript runs on the browser's main thread, unless you create a worker : 除非您创建一个worker ,否则所有JavaScript都在浏览器的主线程上运行:

 function asyncLoop() { for (let i = 0; i <= 400000000; i++) { if (i == 400000000) { self.postMessage('done'); } } } var blob = new Blob(["onmessage = " + asyncLoop.toString()], {type: "text/javascript"}); var worker = new Worker(window.URL.createObjectURL(blob)); worker.onmessage = e => console.log(e.data); worker.postMessage("start"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM