async/await 定义
async/await 实际上是 Promise 的语法糖,它可以用一种更舒适的方式使用 Promise,更易于理解和使用。
async 关键字放在函数前面,表达这个函数总是返回一个 Promise,其他值将自动被包装在一个 resolved 的 Promise 中。
async function f(){
return 1;
}
f().then((v)=>console.log(v));
console.log('f',f())
await 关键字可以暂停函数的执行,直到 Promise 的状态变成已敲定,然后 Promise 的结果继续执行。相比于 promise.then,它显得更为优雅。如果在非 async 中使用,会报语法错误。
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // 等待,直到 promise resolve (*)
alert(result); // "done!"
}
f();
错误处理
如果一个 Promise 正常 resolve,await promise 的结果就是其返回值,否则,将抛出错误。我们可以使用 try/catch 来捕获错误。
async function f() {
try {
let response = await new Promise((resolve, reject) => {
throw new Error('test err')
});
} catch(err) {
console.log(err); // Error: test err
}
}
f();
小练习
如何使用 async 实现 delay 函数, delay 函数定义如下:
delay((str) => str, 3000, 'Hello world').then(res => console.log(res))
答案:参考代码如下:
const sleep = (cb, time, args) => ({
then: (cb) => {
setTimeout(() => cb(args), time);
}
});
const delay = async (cb, time, args) => {
return await sleep(cb, time, args);
};
delay((str) => str, 3000, "Hello world").then((res) => console.log(res)); // Hello world