You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中Promise是同步还是异步?Promise构造函数内代码执行疑问

Promises in Node.js: Sync vs Async Clarification

Great question—this is one of the most common stumbling blocks when learning Promises, so let’s break this down step by step.

1. Is a Promise itself synchronous or asynchronous in Node.js?

Short answer: The Promise object is created synchronously, but its core asynchronous behavior comes from how its resolution handlers (then()/catch()/finally()) are executed.

When you create a Promise, the object itself is instantiated immediately during the synchronous execution of your code. The magic happens later: once the Promise is resolved or rejected, its attached handler callbacks aren’t run right away—they’re queued as microtasks and only execute after the entire current synchronous call stack has been emptied.

2. Is the callback inside the Promise constructor executed synchronously or asynchronously?

100% synchronous. Let’s prove this with a quick code example:

console.log("Start of script");

const myPromise = new Promise((resolve, reject) => {
  // This runs immediately, synchronously
  console.log("Inside Promise constructor callback");
  resolve("Done");
});

console.log("End of script");

If you run this in Node.js, the output will be:

Start of script
Inside Promise constructor callback
End of script

This makes sense because the constructor needs to run your callback right away to kick off whatever operation (async or not) you’re wrapping in the Promise. For example, if you’re wrapping an async filesystem call, you want to start that call immediately, not wait for the event loop to cycle.

Quick Recap

  • Promise creation and its constructor callback are synchronous.
  • The asynchronous part is the execution of then()/catch()/finally() handlers—these are deferred to the microtask queue, running after all synchronous code finishes.

内容的提问来源于stack exchange,提问作者udayakumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:50:08