http://caibaojian.com/es6/async.htmlhttp://caibaojian.com/es6/async.html
async的使用:
没有function关键字,有函数名的,固定写在函数名前面
async init() {
try {
const res = await getInfo()
console.log('数据获取成功')
// 执行后续相应操作
} catch (error) {
console.log(error)
// 执行后续相应操作
}}
有function关键字的,async固定写在function前面
export async function getLocation(){
let myisAuth = await getname();
}
箭头函数
const datas = async ()=> {
const res = await getInfo()
}
const textPromises = urls.map(async url => {
const response = await fetch(url);
return response.text();
});
注意
1:await命令后面的Promise对象,运行结果可能是rejected,所以最好把await命令放在try...catch代码块中。
async init() {
try {
const res = await getInfo()
console.log('数据获取成功')
// 执行后续相应操作
} catch (error) {
console.log(error)
// 执行后续相应操作
}
}
//另一种写法
async myFunction() {
await getInfo()
.catch(function (err) {
console.log(err);
};
}
2:多个await
命令后面的异步操作,如果不存在继发关系,最好让它们同时触发。
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);
// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
3:await
命令只能用在async
函数之中,如果用在普通函数,就会报错。
错误写法:
async function dbFuc(db) {
let docs = [{}, {}, {}];
// 报错
docs.forEach(function (doc) {
await getData(doc);
});
}
正确写法:
async function dbFuc(db) {
let docs = [{}, {}, {}];
let promises = docs.map((doc) => getData(doc));
let results = await Promise.all(promises);
console.log(results);
}
// 或者使用下面的写法
async function dbFuc(db) {
let docs = [{}, {}, {}];
let promises = docs.map((doc) =>getData(doc));
let results = [];
for (let promise of promises) {
results.push(await promise);
}
console.log(results);
}
使用场景:
-
数据库操作或 API 调用等异步操作。
-
需要依次执行多个异步操作的场景。
-
需要在异步操作完成后执行某个操作的场景。