async 函数
函数的返回值为promise对象
promise对象的结果由async函数执行的返回值决定
async function fn1() {
return 1 // 结果: Promise { 1 }
throw 2 // 结果: Promise { <rejected> 2 }
return Promise.xxx // 结果 : Promise { <pending> },必须结合.then一起使用
}
console.log(fn1())
// 结合.then一起使用
async function fn1() {
return Promise.resolve(1)
}
fn1().then(
value=>{
console.log('onResolved ', value)
},
reason => {
console.log('onRejected ', reason)
}
)
await 表达式
await右侧的表达式一般为promise对象,但也可以是其他的值
如果表达式为promise对象,await返回的是promise成功的值
如果表达式是其他值,直接将此值作为await的返回值
async function fn1() {
const res = await fn2()
console.log(res)
}
const fn2 = function(){
return 1
}
fn1()
// 结果为1
//但这个1并不是因为fn2()返回值为1,而是因为fn2执行成功,返回的promise对象结果为1
注意
await必须写在async函数中,但async函数中可以没有await
如果await的promise失败了,就会抛出异常,需要通过try...catch来捕获
async function fn1() {
try {
const res = await fn2()
}catch (e) {
console.log(e)
}
}
const fn2 = function(){
return new Promise((resolve,reject)=>{
reject(3)
})
}
fn1()