How to read file with async/await properly?

前端 未结 7 2138
时光说笑
时光说笑 2020-11-29 17:12

I cannot figure out how async/await works. I slightly understands it but I can\'t make it work.



        
7条回答
  •  遥遥无期
    2020-11-29 18:09

    To use await/async you need methods that return promises. The core API functions don't do that without wrappers like promisify:

    const fs = require('fs');
    const util = require('util');
    
    // Convert fs.readFile into Promise version of same    
    const readFile = util.promisify(fs.readFile);
    
    function getStuff() {
      return readFile('test');
    }
    
    // Can't use `await` outside of an async function so you need to chain
    // with then()
    getStuff().then(data => {
      console.log(data);
    })
    

    As a note, readFileSync does not take a callback, it returns the data or throws an exception. You're not getting the value you want because that function you supply is ignored and you're not capturing the actual return value.

提交回复
热议问题