async await的使用

61 阅读1分钟
// 1.直接从async函数返回非promise值会被自动封装成resolved状态的Promise
async function helloAsync() {
    return "Hello Async"
}

console.log('返回非promise自动转换', helloAsync())
helloAsync().then(res => {
    console.log("res", res)
})

// 2.返回的pending状态的Promise
async function helloAsync2() {
    return new Promise((resolve, reject) => {
    })
}

console.log('返回pending状态的Promise', helloAsync2())
helloAsync2().then(res => {
    console.log("res2", res) // 不会被执行
})

// 3.返回resolved状态的Promise
async function helloAsync3() {
    return new Promise((resolve, reject) => {
            resolve("Hello Async 3")
        }
    )
}

console.log('返回resolved状态的Promise', helloAsync3())
helloAsync3().then(res => {
    console.log("res3", res) //Hello Async 3
})

// 处理异常
// async await中可以多个promise请求,推荐try...catch处理异常(提高错误处理的可读性和健壮性)

async function helloAsync4() {
    try {
        const res1 = await fetch('https://www.baidu.com')
        const res2 = await fetch('https://www.google.com')
        return res1.text() + res2.text()
    } catch (error) {
        console.log('error', error)
    }
}


helloAsync4().then(res => {
    console.log("res4", res)
})

image.png