ES6——promise基础

异步编程:我们经常会遇到下面这种情况:

setTimeout(function () {
    console.log("First");
    setTimeout(function () {
        console.log("Second");
        setTimeout(function () {
            console.log("Third");
        }, 3000);
    }, 4000);
}, 1000);

虽然也能解决任务,但是次数过多的时候就会显得代码很冗余。

ES6推出promise对象刚好解决这个问题;

使用语法:

/**
     * 1.promise基础
    
     */
    new Promise(function (resolve, reject) {
        // 要做的事情...
        console.log('1.Promise基础');
        resolve("abc");     //执行完成,抛出abc
    });

简单的使用:

    /**
     * Promise的各种方法
     */
    new Promise(function (resolve, reject) {
        setTimeout(function(){
            console.log('2.0 Promise基础');
            resolve(1);     //抛出返回值,then接收
        },5000)
    }).then(function (value) {     
        console.log('2.' + value + ' Promise的then方法');
        throw '2'   //抛出错误,catch获取
    }).catch(function (err) {
        console.log('2.' + err + ' Promise的catch方法');
    }).finally(function(){ 
        console.log('2.3 finally方法');
    })
    //备注:最好按 then-catch-finally 的顺序编写程序

进一步的优化:

    /**
     * 异步函数async function中使用 await 指令
    */
    function print(delay, message) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log(message);
                resolve("hello");
            }, delay);
        });
    }

    async function asyncFunc() {
        await print(7000, "First");
        await print(4000, "Second");
        await print(3000, "end");
    }
    asyncFunc();

好,就这样了,基本满足使用

原文地址:https://www.cnblogs.com/xihailong/p/13450885.html