【顶层await】不在async里使用await

设置

1、必须在package.json配置"type": "module",支持顶层await。例:

 "type": "module",

2、Node版本 >= v14.8


用法对比

1.常规用法

  • 常规await只能在async中使用
/**
 * 常规await只能在async中使用
 */

async function fn1() {
    
    
    const p = await Promise.resolve('我是老6')
    console.log(p)
}

fn1()//我是老6

2.顶层用法

  • 不需要在async里使用await
/**
 * 顶层使用
 */

function fn2() {
    
    
    return Promise.resolve('我不是老6呀!')
}

// 直接使用await
const resFn2 = await fn2()
console.log(resFn2)//我不是老6呀!

注意点||错误使用

  • 不能在一个then里使用顶层await,例如↓
/**
 * 错误使用顶层await
 */
const ps1 = Promise.resolve('我是真的老6!')
const ps2 = Promise.resolve('我是真的老6!')

//在ps1的then里使用顶层await
ps1.then(res => {
    
    
    console.log(await ps2())//报错
})

报错图
在这里插入图片描述

正确使用

/**
 * 正确使用顶层await
 */
const ps1 = Promise.resolve('我是真的老6!')
const ps2 = Promise.resolve('我是真的老6!')
 
console.log(await ps1)
console.log(await ps2)

2023/5/12 22:55 晴朗

猜你喜欢

转载自blog.csdn.net/qq_43614372/article/details/130651516