一、什么是Async函数
async函数就是将
Generator
函数的星号(*)
替换成async
,将yield
替换成await
例:(两者相互转换)
//Generator函数表示
const gen = function* () {
const f1 = yield readFile('/etc/fstab');
const f2 = yield readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
};
//async函数表示
const gen = async function () {
const f1 = await readFile('/etc/fstab');
const f2 = await readFile('/etc/shells');
console.log(f1.toString());
console.log(f2.toString());
};
二、async函数的语法
1、返回 Promise 对象
async函数返回一个 Promise 对象。async函数内部return语句
返回的值,会成为then方法
回调函数的参数。
例:
async function f() {
return 'hello world';
}
f().then(v => alert(v))
运行结果:
async函数内部抛出错误,会导致返回的 Promise 对象变为reject(失败)
状态。抛出的错误对象会被catch方法
回调函数接收到。
例:
async function f() {
throw new Error('服务器报错!')
}
f().then(v => alert(v)).catch(err=>alert(err