Promise在节点js中是同步的或异步的

uda*_*mar 9 javascript asynchronous synchronous node.js promise

我承诺很多困惑.这是同步还是异步?

return new Promise (function(resolved,reject){
    //sync or async? 
});
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 19

传递函数为无极构造同步运行,但任何依赖于它的分辨率将异步调用.即使promise立即解析,任何处理程序都将异步执行(类似于你setTimeout(fn, 0)) - 主线程首先运行到最后.

无论您的Javascript环境如何 - 无论您是在Node还是浏览器中,都是如此.

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');
Run Code Online (Sandbox Code Playgroud)


Rya*_*ins 6

Promise 本身并不完全同步或异步。当您创建一个 promise 时,您传递给它的回调会立即执行,并且在该函数产生之前没有其他代码可以运行。考虑以下示例:

new Promise(function(resolve, reject) {
  console.log('foo');
})
console.log('bar');
Run Code Online (Sandbox Code Playgroud)

承诺外的代码必须等待承诺内的代码(同步)完成才能开始执行。

也就是说,promise 是处理异步代码的常用方法。Promise 最常见的用例是表示一些以异步方式生成或获取的值。依赖于该值的逻辑可以通过向.then()Promise 方法或相关的 Promise 方法注册回调来异步等待该值可用。


Oma*_*iaa 6

这段代码更清楚地说明了这一点:

\n
        console.log("0");\n        new\xc2\xa0Promise((resolve,\xc2\xa0reject)\xc2\xa0=>\xc2\xa0{\n        \xc2\xa0\xc2\xa0console.log("1");\n        \xc2\xa0\xc2\xa0resolve();\n        }).then(()\xc2\xa0=>\xc2\xa0{\n        \xc2\xa0\xc2\xa0console.log("2");\n        });\n        console.log("3");\n
Run Code Online (Sandbox Code Playgroud)\n

代码打印: 0 1 3 2\n所以,then异步运行,而主回调函数同步运行。

\n