Promise is synchronous or asynchronous in node js

前端 未结 6 1965
滥情空心
滥情空心 2020-12-10 02:47

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

return new Promise (function(resolved,reject){
    //sync or async? 
});
         


        
6条回答
  •  隐瞒了意图╮
    2020-12-10 02:57

    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');

提交回复
热议问题