zoukankan      html  css  js  c++  java
  • koa2 async和await 实战详解

    基本用法


    • async 表示这是一个async函数,await只能用在这个函数里面。

    • await 表示在这里等待promise或者等待async函数中的promise返回结果了,再继续执行。

    • Promise 对象代表一个异步操作,有三种状态:Pending(进行中)、Resolved(已完成,又称 Fulfilled)和 Rejected(已失败)。Promise 对象的状态改变,只有两种可能:用 resolve 方法将 Promise 对象的状态,从「未完成」变为「成功」(即从 pending 变为 resolved)和用 reject 方法将 Promise 对象的状态,从「未完成」变为「失败」(即从 pending 变为 rejected)。

    第一个例子: await只能用在async函数


    • 错误示例1:程序不能运行

    let funPromise = function (time) {
        return new Promise(function (resolve, reject) {
            //Pending 进行中
            setTimeout(function () {
                resolve(); // 从 pending 变为 resolved
            }, time);
        })
    };
    
    let funAsync = async function () {
        let numArr = [1003, 1002, 1001];
        // 会报错 await没有在async函数中
        numArr.forEach(function(value, index){
            await funPromise(value);
        })
    }
    
    funAsync();
    
    • 错误示例2:程序能运行,结果不是我们想要的

    let funPromise = function (time) {
        return new Promise(function (resolve, reject) {
            //Pending 进行中
            setTimeout(function () {
                // 从 pending 变为 resolved
                resolve(time + ' : ' + new Date()); 
            }, time);
        })
    };
    
    let funAsync = async function () {
        let numArr = [1003, 1002, 1001];
        numArr.forEach(async function(value, index){
            //三个funPromise()操作将是并发执行,也就是同时执行,而不是继发执行
            let result = await funPromise(value);
            console.log(result);
        })
    }
    
    funAsync();
    
     
    第一个例子错误示例2的运行结果
    • 正确示例

    let funPromise = function (time) {
        return new Promise(function (resolve, reject) {
            //Pending 进行中
            setTimeout(function () {
                // 从 pending 变为 resolved
                resolve(time + ' : ' + new Date());  
            }, time);
        })
    };
    
    let funAsync = async function () {
        let numArr = [1003, 1002, 1001];
        // 三个funPromise()操作将是继发执行
        for (let value of number){
            let result = await funPromise(value);
            console.log(result);
        }
    }
    
    funAsync();
    
     
    第一个例子正确示例子的运行结果

    第二个例子:await等待promise返回结果


    let funPromise = function (time) {
        return new Promise(function (resolve, reject) {
            //Pending 进行中
            setTimeout(function () {
                resolve(); // 从 pending 变为 resolved
            }, time);
        })
    };
    
    let funAsync = async function () {
        // 在这里使用起来就像同步代码那样直观
        console.log('start:  ' + new Date());
        await funPromise(3000);
        console.log('end:  '  + new Date());
    };
    
    funAsync();
    
     
    第二个例子的运行结果

    第三个例子:等待async函数中的promise返回结果


    let funPromise = function (time) {
        return new Promise(function (resolve, reject) {
            //Pending 进行中
            setTimeout(function () {
                resolve(); // 从 pending 变为 resolved
            }, time);
        })
    };
    
    let funAsync_1 = async function () {
        console.log('funAsync_1_start:  ' + new Date());
        await funPromise(3000);
        console.log('funAsync_1_end:  '  + new Date());
    };
    
    let funAsync_2 = async function () {
        console.log('funAsync_1_start:  ' + new Date());
        // 等待 funAsync_1() 中的 Promise 运行结束
        await funAsync_1();
        console.log('funAsync_1_end:  '  + new Date());
    };
    
    funAsync_2();
    
     
    第三个例子的运行结果

    注意点


    • await 命令后面的 Promise 对象,运行结果可能是 rejected,所以最好把 await 命令放在 try...catch 代码块中。

    let funPromise = function (time) {
        return new Promise(function (resolve, reject) {
            //Pending 进行中
            setTimeout(function () {
                reject('我是返回的错误'); // 从 pending 变为 rejected
            }, time);
        })
    };
    
    let funAsync = async function () {
        console.log('start:  ' + new Date());
        try {
            await funPromise(3000);
            console.log('我不会执行的噢');
        }  catch (err) {
            console.log(err);
        }
        console.log('end:  '  + new Date());
    };
    
    funAsync();
    
     
    注意点的程序运行结果

    源码查看


    https://github.com/yangxiaopingios/koaExample/blob/master/code/script/oneExample.js



    作者:码农随想录
    链接:https://www.jianshu.com/p/f8cfb82b4dad
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    漫思
  • 相关阅读:
    struts2标签解释
    通过注册表修改XP默认登陆用户
    6类常见开机故障
    摩尔定律
    小红伞扫描病毒类型
    newInstance()方法和new关键字
    常见恶意软件种类及说明
    jquery1.9 中这些方法已经被删除(live、die、sub........)
    (转)Ubuntu下JDK7安装全过程并调试第一个带包的java程序
    js取消气泡事件、阻止浏览器的默认行为
  • 原文地址:https://www.cnblogs.com/sexintercourse/p/14419297.html
Copyright © 2011-2022 走看看