Promise

2017-08-01  本文已影响0人  8d2855a6c5d0
var p = Promise.all([p1, p2, p3]);

上面代码中,Promise.all方法接受一个数组作为参数,p1、p2、p3都是 Promise 实例,如果不是,就会先调用下面讲到的Promise.resolve方法,将参数转为 Promise 实例,再进一步处理。(Promise.all方法的参数可以不是数组,但必须具有 Iterator 接口,且返回的每个成员都是 Promise 实例。)

Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))

一个简单的promise

class Promise {
    constructor() {
        this.callbacks = [];
    }

    then(onsuccess, onfail) {
        this.callbacks.push({
            resolve: onsuccess,
            reject: onfail
        });
        return this
    }
    
    resolve(result){
        this.complete('resolve',result);
    }
    reject(result){
        this.complete('reject',result);
    }
    complete(type,result){
        var callbackObj = this.callbacks.shift();
        callbackObj[type](result);
    }
}


var p = new Promise();
function fn() {
    console.log('fn');
    setTimeout(function () {
        p.reject('data1');
    },1000);
    return p;
}

function fn1(result) {
    console.log('fn1',result);
    setTimeout(function () {
        p.resolve('data2');
    },1000);
}

function fn2(result) {
    console.log('fn2',result);
}

function fn3(result) {
    console.log('fn3',result);
}


fn().then(fn1,fn3).then(fn2);
上一篇 下一篇

猜你喜欢

热点阅读