How to read file with async/await properly?

前端 未结 7 2137
时光说笑
时光说笑 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:14

    You can easily wrap the readFile command with a promise like so:

    async function readFile(path) {
        return new Promise((resolve, reject) => {
          fs.readFile(path, 'utf8', function (err, data) {
            if (err) {
              reject(err);
            }
            resolve(data);
          });
        });
      }
    

    then use:

    await readFile("path/to/file");
    

提交回复
热议问题