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

async函数未等待变量存储完成就执行后续代码该如何修复

问题原因

你当前使用的是回调风格的fs.readFile,这类回调式API本身不返回Promise对象,所以await关键字在这里不会生效,不会等待回调函数执行完毕就会直接运行后续的console.log语句,自然拿不到赋值后的my_content。额外说明:JSON.parse是同步方法,不需要加await调用。


修复方案

方案1:使用Node.js内置Promise化fs API(推荐)

Node.js 10+ 版本的fs模块自带Promise版本的实现,存放在fs/promises路径下,直接用await调用即可:

// 引入promise版本的fs模块
const fs = require('fs/promises');

async function getContent(){
  let my_content;
  try {
    // 直接await读取文件的返回结果
    const content = await fs.readFile('credentials.json');
    my_content = JSON.parse(content);
  } catch (err) {
    console.log('Error loading client secret file:', err);
  }
  console.log(my_content);
}

方案2:手动封装回调API为Promise

如果使用的Node版本较低不支持fs/promises,可以手动把回调式readFile包装为返回Promise的方法:

const fs = require('fs');

// 手动封装为返回Promise的读取方法
function readFilePromise(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, content) => {
      if (err) return reject(err);
      resolve(content);
    })
  })
}

async function getContent(){
  let my_content;
  try {
    const content = await readFilePromise('credentials.json');
    my_content = JSON.parse(content);
  } catch (err) {
    console.log('Error loading client secret file:', err);
  }
  console.log(my_content);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:57:03