Await for asynchronous function results in undefined

主宰稳场 提交于 2019-12-07 13:08:51

问题


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();

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


回答1:


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));
    });
  });
}

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);

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.




回答2:


You missed promise resolve and reject.

Use as below.

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

               resolve(json_data);

           });
    }
});



回答3:


try it:

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

              resolve(json_data);
           });

   }


来源:https://stackoverflow.com/questions/47789093/await-for-asynchronous-function-results-in-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!