多个 Promise 顺序执行

2018-07-22sad creeper

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


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


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


const ajax3 = () => timeout(2000).then(() => {
console.log('3');
return 3;
});


const mergePromise = ajaxArray => {
let p = Promise.resolve();
return Promise.all(ajaxArray.map(item => {
p = p.then(item);
return p;
}));
};


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




//输出
//1
//2
//3
//done
//[1,2,3]

阅读 430 评论


null

test

5个月前 ·

null

回复 :test

5个月前 ·