Promise在Node JS中是同步还是异步 [英] Promise is synchronous or asynchronous in node js

查看:283
本文介绍了Promise在Node JS中是同步还是异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对诺言充满困惑.是同步还是异步?

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

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

推荐答案

您将传递给的函数Promise构造函数是同步运行的,但是取决于其分辨率的任何内容都将被异步调用.即使promise立即解决,任何处理程序都将异步执行(类似于setTimeout(fn, 0)时)-主线程首先运行到末尾.

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.

无论您是使用Javascript环境还是使用Node还是浏览器,都是如此.

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

这篇关于Promise在Node JS中是同步还是异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆