async 声明"这是个异步函数",await 表示"在这里等它出结果"。配合使用,让异步代码写得跟同步代码一样。
| 以前 · .then 回调 | 现在 · async / await |
|---|---|
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve("数据来了"), 500);
});
}
getData().then(data => {
console.log(data); // 数据来了
});
|
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve("数据来了"), 500);
});
}
async function main() {
let data = await getData(); // 等它出结果
console.log(data); // 数据来了
}
main();
|
以前拿到 Promise 要用 .then 接住;现在在 async 函数里用 await 一等,结果直接当普通变量用,代码跟同步一样。
| 以前 · .catch | 现在 · try...catch |
|---|---|
getData().then(data => {
console.log(data);
}).catch(err => {
console.log("失败:", err);
});
|
async function main() {
try {
let data = await getData();
console.log(data);
} catch (err) {
console.log("失败:", err);
}
}
main();
|
以前失败走 .catch;现在用 try...catch,跟处理普通代码出错一模一样,不用专门记 Promise 那套。
function getData(name) {
return new Promise(resolve => {
setTimeout(() => resolve(name + "的数据"), 300);
});
}
async function main() {
let a = await getData("第一个");
let b = await getData("第二个");
console.log(a);
console.log(b);
// 第一个等完才等第二个,顺序清清楚楚
}
main();
await 会"拦住"代码,上一行等完才执行下一行,不用再 .then 里套 .then。
// ① await 只能写在 async 函数里面
// ② async 函数返回的值,一定被包成 Promise
async function fn() {
return 123; // 这个 123 被包成 Promise
}
fn().then(v => console.log(v)); // 123
async 函数里 return 的值,外面要用 .then 或再 await 才能拿到;await 离开 async 函数会报错。