async函数修饰符
被async修饰的函数特点:
- 返回一个Promise对象,可以使用then(data=>{})添加回调函数
- 还可以作为普通函数运行,但函数里面可以使用 await 关键字
async函数返回的是Promise对象
async function f1(){
return 1
}
async function f2(){
return Promise.resolve(2)
}
const result1 = f1()
const result2 = f2()
console.log(result1);
console.log(result2);
//f1虽然返回的是1,系统会自动给我们封装成一个promise对象给我们返回
await相当于promise.then成功的情况
// 也就是说,promise.resolve() 就相当于 await
async function fn(){
const p = Promise.resolve('成功')
p.then(data=>{
console.log('data_then',data);
})
let await_Data = await p
console.log('await_Data',await_Data);
}
fn()
//data_then 成功
// await_Data 成功
//可以可看出,p.then 可以用 await p 替代,
// 结合(一、await自动封装Promise), await 4 其实等于 await Promise.resolve(4)
Promise.catch 异常的情况,对应try…catch
async function fn(){
const p = Promise.reject('失败')
// then写法
p.then((res,rej)=>{
console.log('data_then',res,rej);
}).catch(e=>console.log(e))
// await 写法
try{
let await_Data = await p
console.log('await_Data',await_Data);
}catch(e){
console.log('error',e);
}
}
fn()
//error 失败
//失败