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:
out
done
then
What am I missing?
Your loop is inside the callback that you passed to new Promise
. This function is called the 'executor':
function executor(resolve, reject)
The executor is called synchronously by new Promise
. The role of the executor is to set up any asynchronous events in order to have resolve
or reject
eventually called.
See MDN: Promise constructor parameters
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. To make a process "kind of async", you could use 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. See Using promises on MDN for more.
JavaScript is single-threaded with an event loop. .then
and setTimeout
schedule events.
All JavaScript runs on the browser's main thread, unless you create a worker :
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.