Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have lot of confusion in promise. It's a synchronous or asynchronous ?

return new Promise (function(resolved,reject){
    //sync or async? 
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
465 views
Welcome To Ask or Share your Answers For Others

1 Answer

The function you pass into the Promise constructor runs synchronously, but anything that depends on its resolution will be called asynchronously. Even if the promise resolves immediately, any handlers will execute asynchronously (similar to when you setTimeout(fn, 0)) - the main thread runs to the end first.

This is true no matter your Javascript environment - no matter whether you're in Node or a browser.

console.log('start');
const myProm = new Promise(function(resolve, reject) {
  console.log('running');
  resolve();
});
myProm.then(() => console.log('resolved'));
console.log('end of main block');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...