等待异步函数导致未定义 [英] Await for asynchronous function results in undefined

查看:108
本文介绍了等待异步函数导致未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与Node异步/等待时遇到了麻烦.当我尝试这样做时:

I'm having trouble with async/await with Node. When I try this:

function Read_Json_File() {
   fs.readFile('import.json','utf-8',(err, data) => {  
       if (err) throw err;
       json_data = JSON.parse(data);

       return json_data;

   });
}

async function run_demo() {
    let get_json_file = await Read_Json_File();
    console.log(get_json_file);
}

run_demo();

它从文件中返回undefined而不是JSON.为什么不等待文件读取完成?

It returns undefined instead of the JSON from the file. Why doesn't it wait for the file reading to finish?

推荐答案

您没有从Read_Json_File返回任何内容,因此未定义-您从回调返回的数据没有任何结果.相反,要使用async/await,您需要对fs.readFile进行承诺,因为它尚未.然后,您将可以使用async/await:

You're not returning anything from Read_Json_File, thus you get undefined -- you're returning data from the callback which doesn't result in anything. Instead, to use async/await, you'd need to promisify fs.readFile since it's not already. Then you'll be able to use async/await:

function readJSONFile() {
  return new Promise((resolve, reject) => {
    fs.readFile('import.json', 'utf-8', (err, data) => { 
      if (err) reject(err);
      resolve(JSON.parse(data));
    });
  });
}

等待需要实际的 promise 来等待.这样做是返回一个使用等待的承诺.因此,我们等到调用resolve -在完成加载JSON时发生:

Await requires an actual promise to wait for. What this does is return a promise to use await on. Thus, we wait until we call resolve - which happens when we're done loading the JSON:

let json = await readJSONFile();
console.log(json);

在这里我们称为readJSONFile.这将返回一个承诺,该承诺将解决JSON文件加载完成的时间,并允许看似同步执行异步代码.

Here we call readJSONFile. This returns a promise which resolves when the JSON file is done loading, and allows for seemingly synchronous execution of asynchronous code.

这篇关于等待异步函数导致未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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