async await的用法

时间:2023-03-09 16:53:48
async  await的用法
const fs = require('fs');

const readFile = function (fileName) {
return new Promise(function (resolve, reject) {
fs.readFile(fileName, "utf-8",function(error, data) {
if (error) return reject(error);
resolve(data);
});
});
}; const gen = async function() { const f1 = await readFile('./data1.txt');
const f2 = await readFile('./data2.txt');
console.log(f1);
console.log(f2);
}; gen();

  上面是读取两个文件的例子

和co模块相比较

co模块约定,yield命令后面只能是 Thunk 函数或 Promise 对象,而async函数的await命令后面,可以是 Promise 对象和原始类型的值(数值、字符串和布尔值,但这时等同于同步操作)。