node.js - 关于下面代码中的事件循环,nodejs 和浏览器有什么区别?

标签 node.js

async function async1() {
    console.log("a");
    await  async2(); 
    console.log("b");
}
async function async2() {
   console.log( 'c');
}
console.log("d");
setTimeout(function () {
    console.log("e");
},0);
async1();
new Promise(function (resolve) {
    console.log("f");
    resolve();
}).then(function () {
    console.log("g");
});
console.log('h');

nodejs 运行时输出:d a c f h b g e

Google 浏览器运行时输出:d a c f h g b e

为什么输出不同的结果?

最佳答案

我认为是因为 NodeJS 有自己的计时器实现:

https://nodejs.org/dist/latest-v9.x/docs/api/timers.html

The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.

关于 Node 中的事件循环:https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

关于node.js - 关于下面代码中的事件循环,nodejs 和浏览器有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49546738/

相关文章:

javascript - 未存储 SetCookie header

javascript - 从 js 文件中获取对象作为字符串读取并使用 gulp 处理成单个文件

javascript - 如何创建共享的、特权的、公共(public)的方法?

node.js - 在集群中运行 meteor 并实时更改

javascript - express-jwt 身份验证中间件不工作

node.js - 在 React 项目上运行 NPM start 后出错

node.js - 如何在不使用 native 模块的情况下将 Node.js 应用程序连接到 MongoDB?

javascript - 使用promisefiy all时出错

javascript - Node.js页面刷新后,如何获取新生成的数据

node.js - 尝试安装 Nodegit 时如何修复此 gyp 重建错误?