一;async

1.函数前面加上 async 关键字,则该函数会返回一个结果为 promise 的对象。

2. async 函数返回 promise 对象的状态。

2.1:如果返回的是一个非 Promise 类型的数据, 则async 函数返回 promise 的状态 为 fulfilled 成功。

2.2:如果返回的是一个 Promise对象,则 async 函数返回 promise 的状态由返回的Promise对象的状态决定。

2.3:如果 throw Errow 抛出异常,则 async 函数返回 promise 的状态为 rejected 失败。

二;await

1.await 右侧的表达式一般为 promise 对象。

2.await 是在等一个表达式的结果,等一个返回值(回调成功的内容)

3.如果 await 右侧是一个 promise 对象,则 await 返回的是 promise 成功的值。

注意:

1.await 必须写在 async 函数中,但 async 函数中可以没有 await。

2.如果 await 的 promise 失败了,就会抛出异常,该异常需要通过 try catch 捕获处理。

3.如果它等到的是一个 Promise 对象,await 就忙起来了,它会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。

async function main(){
            let p = new Promise((resolve,reject)=>{
                resolve('ok')
            })
            try {
                // 如果 await 后面的 promise是成功的,则返回成功的内容
                let res = await p
                console.log(res);
            }
            // 如果 await 右侧的 promise状态为错误,则需要通过catch捕获错误信息
            catch (error) {
                // error 接收的是 promise错误的返回值
                console.log(error);
            }
        }
        main()

 三;async 和 await 结合发送 ajax 

1.封装一个 发送GET请求的 promise

function sendAjax(url) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest()
                xhr.open('GET', url)
                xhr.send()
                // 处理返回结果
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        // 判断状态码
                        if (xhr.readyState >= 200 && xhr.readyState < 300) {
                            resolve(xhr.response)
                        }else {
                            reject(xhr.status)
                        }
                    }
                }
            })
        }

2.async和await结合发送ajax请求

// 触发点击事件发送ajax请求
        let btn = document.querySelector('#btn')
        btn.addEventListener('click', async function () {
            try {
                let res = await sendAjax('get请求地址')
                console.log(res);
            } catch (error) {
                console.log(error);
            }
        })

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐