Basic use of async await

Use of async await

自我记录

MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference /Operators/await

1. async function

The function return value is a promise object.
The result of the promise object is determined by the return value of the async function execution.

async function main() {
    
    
     // 1.如果返回值 是一个非Promise类型的数据
     // 返回的结果就是 一个成功的 Promise 对象 PromiseState状态 fulfilled
     // 并且return 什么 PromiseResult 结果就是什么
     // return 'abc'

     // 2.如果返回值 是一个Promise类型的数据
     // 返回的结果就是 Promise 结果的状态
     // return new Promise((resolve, reject) => {
    
    
     //     // resolve('成功')
     //     reject('失败')
     // })

     // 3.如果抛出异常
     // 状态就是一个失败的Promise对象 结果就是 抛出的结果
     throw 'err'
 }
 let res =  main()
 console.log(res);

Insert image description here

2.await expression

1. The expression on the right side of await is generally a promise object, but it can also be other values
​​2. If the expression is a promise object, await returns the value of successful promise
3. If the expression is other values, this value is directly used as return value of await

async function main() {
    
    
    let p = new Promise((resolve, reject) => {
    
    
        resolve('成功')
    })
    // 1.右侧为promise的情况
    let res = await p
    console.log(res); // 打印   成功

    // 2.右侧为其它类型的数据 一般很少见
    let res2 = await 'abc'
    console.log(res2); // 打印  abc   
}
main()

3. Attention

await must be written in the async function, but there is no need for await in the async function
. If the promise of await fails, an exception will be thrown and needs to be captured and processed through try...catch

async function main() {
    
    
    let p = new Promise((resolve, reject) => {
    
    
        reject('err')
    })
    try {
    
    
        let res3 = await p
        console.log(res3);
    } catch(e) {
    
    
        console.log(e); // 打印 err
    } finally{
    
    
        // 补充知识点 finally 无论成功失败都会执行
        console.log('无论成功失败 我都会执行!');
    }
}
main()

Guess you like

Origin blog.csdn.net/zhgweb/article/details/131063883