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

Node.js中如何等待回调更新变量后再打印该变量?

Node.js中回调函数执行后再打印变量的解决方案

你遇到的问题本质是异步代码的执行顺序问题:functionWithCallbackWhichPopulatesTestVariableWithWordSecond是异步函数,程序调用它后不会等待其内部操作完成,会直接执行后面的打印语句,这时候回调还没修改testVariable,所以输出的是初始值"first"。

解决的核心是把打印逻辑放到回调函数里,确保只有当变量更新完成后才执行打印。以下是具体实现:

方案一:直接利用回调函数

var testVariable = "first";

// 模拟你的带回调函数(实际场景可能是IO操作、API请求等异步逻辑)
function functionWithCallbackWhichPopulatesTestVariableWithWordSecond(callback) {
  // 用setTimeout模拟异步操作
  setTimeout(() => {
    testVariable = "second";
    callback(); // 异步操作完成后触发回调
  }, 100);
}

// 调用函数时,在回调内执行打印
functionWithCallbackWhichPopulatesTestVariableWithWordSecond(() => {
  console.log(testVariable); // 输出 "second"
});

方案二:用Promise+async/await简化异步逻辑(避免回调嵌套)

如果不想写嵌套的回调,可以把原函数封装成Promise,再用async/await来等待异步操作完成:

var testVariable = "first";

// 封装原回调函数为Promise
function updateTestVariable() {
  return new Promise((resolve) => {
    setTimeout(() => {
      testVariable = "second";
      resolve();
    }, 100);
  });
}

// 用async函数等待异步操作
async function run() {
  await updateTestVariable();
  console.log(testVariable); // 输出 "second"
}

run();

不管用哪种方式,核心都是让打印逻辑等待异步操作完成后再执行,而不是在异步函数调用后直接执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:45:12