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

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

问题描述

我对承诺有很多困惑.它是同步的还是异步的?

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

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

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