了解Promise

113 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

Promise是什么?直接输出看一下吧console.dir(Promise)

image.png

Promise是一个构造函数,自己身上有all、resolve这几个方法,原型上有then等同样很眼熟的方法。这么说用Promise new出来的对象肯定也有then方法

试验一下吧

var NewPromise = new Promise(function(resolve, reject){
    //做一些异步操作
    setTimeout(function(){
        console.log('执行完成');
        resolve('执行成功了');
    }, 2000);
});

在上面的代码中,我们执行了一个异步操作,也就是setTimeout2秒后,输出“执行完成”,并且调用resolve方法。

需要注意的一个细节。所以我们用Promise的时候一般是包在一个函数中,在需要的时候去运行这个函数

function Async(){
    var NewPromise = new Promise(function(resolve, reject){
        //做一些异步操作
        setTimeout(function(){
            console.log('执行完成');
            resolve('执行成功了');
        }, 2000);
    });
    return NewPromise;            
}
Async()

疑问?这个干嘛用的?在开始,我们在原型上面看到了有个。then方法吧,在上面中,我们将Promise对象return出来了,我们所以就得到了一个Promise对象

//then接收一个参数,是函数,并且会拿到我们在Async中调用resolve时传的的参数

Async().then(function(data){
    console.log(data)    //执行成功了
})

结果

image.png

Promise的精髓是“状态”,用维护状态、传递状态的方式来使得回调函数能够及时调用

//优雅的解决回调地狱

function Async() {
        var NewPromise = new Promise(function (resolve, reject) {
            //做一些异步操作
            setTimeout(function () {
                console.log('异步任务1');
                resolve('1');
            }, 2000);
        });
        return NewPromise;
    }

function Async2() {
        var NewPromise = new Promise(function (resolve, reject) {
            //做一些异步操作
            setTimeout(function () {
                console.log('异步任务2执行完成');
                resolve('2');
            }, 2000);
        });
        return NewPromise;
    }


Async()
.then(function(data){
    console.log(data);
    return Async2();
})
.then(function(data){
    console.log(data);
})

image.png

all的使用

Promise
        .all([Async(), Async2()])
        .then(function(data){
            console.log(data);
        })

all会把所有异步操作的结果放进一个数组中传给then

image.png