ECMA Script 6_async 函数

async 函数

  •     const promise = new Promise((resolve, reject)=>{
            setTimeout(function(){
                console.log("Done1"+"First");
                resolve("Done1"+"First");
            }, 1000);
        });
    async function fn(){
        console.log("开始执行!");
    
        // 只能在 async 函数里使用
        await 123;    // 只能在 async 函数里使用
    
        // 只能在 async 函数里使用
        await promise;    // 异步等待,须包装成 Promise 对象
    
        console.log("执行完了!");
    };
    
    fn();

真正意义上去解决异步回调的问题,

同步流程 表达 异步操作

本质上就是: Generator 的语法糖

  • await promise;

等待异步操作

只会 等待 初始化状态Promise 实例(如果是失败状态,会报错)

  • const promise = new Promise((resolve, reject)=>{
        setTimeout(function(){
            resolve("1");
        }, 1000);
    });
    
    async function fn(){
        console.log('开始执行');
        
        const result1 = await promise;
        console.log(result1);
        
        const result2 =  await new Promise((resolve, reject)=>{
            setTimeout(function(){
                resolve('2');    // 如果这里 reject() 则下面的代码都不会执行了
            }, 2000);
        });
    
        const result3 = await new Promise((resolve, reject)=>{
            setTimeout(function(){
                resolve('3');
            }, 3000);
        });
    };
    
    var ret = fn();
    console.log(ret);    // 默认返回值 就是Promise 实例
    
    ret.then(result=>{
        console.log('全部都成功了');
        console.log(result);    // 如果没有返回值,默认 unfefined
    }).catch(result=>{
        // 必须是 await 修饰的 promise 实例,且必须 失败状态
        console.log('Something is wrong!');
    }); 

 

posted @ 2018-12-15 17:15  耶梦加德  阅读(159)  评论(0编辑  收藏  举报