如何详细解释JavaScript中async和await的用法和原理?
摘要:async 函数永远会返回一个promise,即使你在函数中没有返回任何值。 async 函数永远会返回一个promise,即使你在函数中没有返回任何值。 因为:返回没有返回值时函数默认返回的是 undefined. 所以:会返回一个 pr
async 函数永远会返回一个promise,即使你在函数中没有返回任何值。
async 函数永远会返回一个promise,即使你在函数中没有返回任何值。
因为:返回没有返回值时函数默认返回的是 undefined.
所以:会返回一个 promise,这个 promise 的 值为 undefined。
async function doThingFn(){
console.log('doThingFn')
}
// async 函数永远会返回一个promise,即使你在函数中没有返回任何值。
console.log(111, doThingFn())
// 输出的值是 undefined
// 因为async 函数会返回一个promise, 所以我们是可以写then的。
doThingFn().then(res=>{
console.log('输出的值是',res)
})
async 函数的返回是Promise.resolve
async function doThingFn(){
console.log('doThingFn')
}
等于与下面的
async function doThingFn(){
// 返回没有返回值时函数默认返回的是 undefined.
return Promise.resolve(undefined)
}
当 await 遇到一个被拒绝的 Promise 时,它会抛出异常。因此需要被捕获
下面依次输出的结果是:A
async function doThingFn(){
console.log('A')
const result2 = await Promise.reject('B')
console.log('C')
return Promise.reject('D' )
}
doThingFn()
为啥只会输出:A ?
因为当 await 遇到一个被拒绝的 Promise 时,它会抛出异常。我们没有捕获,直接就会报错的。
因此下面的 C 不会输出。
为啥不会输出 C
async function doThingFn(){
try{
console.log('A')
const result2 = await Promise.reject('B')
console.log('C')
}catch(err){
console.log('err',err)
}
}
doThingFn()
分析:当 await 遇到被拒绝的 Promise 时(就是说:Promise.reject):
立即抛出异常,中断当前代码块的执行。
(如果有catch), 直接跳转到最近的 catch 块
await 之后的代码不会执行,因此不会输出 C。
如何让他输出C
async function doThingFn(){
try{
console.log('A')
// 我们在这里将它捕获掉。
