顺序执行Promise

在promise中,then返回的依然是个promise;
回调函数中会把上一个then中返回的值当做参数值供当前then方法调用。
then方法执行完毕后需要返回一个新的值给下一个then调用(没有返回值默认使用undefined)。
每个then只可能使用前一个then的返回值。

const timeout = ms => new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, ms);
});

const ajax1 = () => timeout(2000).then(() => {
    console.log('1');
    reject();
    return 1;
});

const ajax2 = () => timeout(1000).then(() => {
    console.log('2');
    return 2;
});

const ajax3 = () => timeout(2000).then(() => {
    console.log('3');
    return 3;
});
mergePromise = ajaxArray => {
    var data=[];
    let p=new Promise(function(resolve,reject){
        resolve();
    });
    for(let i=0;i<4;i++){
        p=p.then(function(id){
            if(i>0){
                data.push(id);
            }
            if(i==3){
                return new Promise(function(resolve,reject){resolve(data)});
            }
            return ajaxArray[i]();
        })
    }
    return p;
};

mergePromise([ajax1, ajax2, ajax3]).then(data => {
    console.log('done');
    console.log(data); // data 为 [1, 2, 3]
});

一个 promise 必须提供一个 then 方法以访问其当前值、终值和据因。

promise 的 then 方法接受两个参数:

promise.then(onFulfilled, onRejected) Todo:这里只介绍onFulfilled,所以删除了关于onRejected的规范定义

onFulfilled 和 onRejected 都是可选参数。

如果 onFulfilled 不是函数,其必须被忽略
如果 onFulfilled 是函数:

当 promise 执行结束后其必须被调用,其第一个参数为 promise 的终值
在 promise 执行结束前其不可被调用
其调用次数不可超过一次

猜你喜欢

转载自blog.csdn.net/lay136362687/article/details/81149836