1.async作用:使异步操作更加方便 2.async修饰的函数 会返回Promise对象 可用then catch方法 3.async是generator的一个语法糖
async function f() {
let str = await 'hello world'; //await后面的内容会自动转成Promise对象
let data = await str.split('');
return data;
}
//如果async函数中有多个await 则会等待所有await执行完,获得结果,再去执行then和catch
f().then(data => {
console.log(data)
}).catch(error => {
console.log(error)
});
一旦遇到reject 将不再往下执行
async function f2() {
// await Promise.reject('出错了'); //一旦遇到reject 将不再往下执行
// await Promise.resolve('hello');
try {
await Promise.reject('出错了');
} catch (error) {
}
return await Promise.resolve('hello');
}
f2().then(v => console.log(v)).catch(e => console.log(e));