ES6 —— 学习之七

1. async 与 await

  • 1)async 函数
  • async 函数是什么?一句话,它就是 Generator 函数的语法糖。async 函数的返回值为 promise 对象, promise 对象的结果由 async 函数执行的返回值决定
async function fn() {
    // 返回一个 非Promise类型的对象
    // return 'Qinghuan';
    // return;

    // 抛出错误
    // throw new Error('出错啦!')

    // 当返回一个Promise对象
    return new Promise((resolve, rejected)=>{
        // rejected('出错啦!');
        resolve('成功啦!');
    })
}

const result = fn();
// 当返回结果不是一个 Promise类型的对象,result 是一个 成功 的 Promise 对象
// [[PromiseState]]: "fulfilled"
// [[PromiseResult]]: "Qinghuan"

// 当返回结果是抛出错误的时候,result 是一个 失败的 Promise 对象
// [[PromiseState]]: "rejected"
// [[PromiseResult]]: Error: 出错啦!

result.then(success =>{
    console.log(success);   // 成功啦!
}).catch(error =>{
    console.log(error);
})
  • 2)await
  • await 必须写在 async 函数中
  • await 右侧的表达式一般为 promise 对象
  • await 返回的是 promise 成功的值
  • await 的 promise 失败了, 就会抛出异常, 需要通过 try...catch 捕获处理
const p = new Promise((resolve, rejected)=>{
    // resolve('请求成功');
    rejected('请求失败');
})

// await 必须跟在async函数里面
async function fn() {
    try {
        let result = await p;
        console.log(result);
        // 当 Promise 对象是返回成功的时候 result 是一个成功的Promise对象
        // [[PromiseState]]: "fulfilled"
        // [[PromiseResult]]: "请求成功"
    } catch(e) {
        // 当 Promise 对象是返回失败的时候,catch 捕捉错误
        //  e 参数就是 Promise 对象中 rejected 返回的数据
        console.log(e);
    }
}

fn();
  • 3)async 与 await 结合使用
function sendAJAX(url){
    return new Promise((resolve, rejected)=>{
        const x = new XMLHttpRequest();
        x.open('GET',url);
        x.send();
        x.onreadystatechange = function() {
            if (x.readyState === 4) {
                if (x.status >= 200 && x.status < 300) {
                    resolve(x.response);
                } else{
                    rejected(x.status);
                }
            }
        }
    })
}

async function main() {
    try{
        let blogs = await sendAJAX('http://139.9.60.105:10520/article/indexSel');
        console.log(blogs);     // 请求成功返回的数据
        let jokes = await sendAJAX('https://api.apiopen.top/getJoke');
        console.log(jokes);     // 请求成功返回的数据
    }catch(e){
        console.log(e);
    }
}

main();
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容