js promise对象数组,使用reduce序列化执行

发布时间 2023-06-28 17:43:48作者: 夏几把狂舞

自己使用mdn官方例子测试了一下,发现还有一些小问题,调试了一下OK了。

const timeOut = function(ms){
return new Promise(function(resolve){
return setTimeout(resolve, ms);
})
}

var p1 = function() {
return new Promise(function (resolve){
console.log(new Date() + ' p1 赋值');
// setTimeout(() => {
// console.log(new Date() + ' resolve(aaa)');
// resolve('aaa');
// }, 1000);
timeOut(1000).then(function(){
console.log(new Date() + ' p1 timeOut赋值');
resolve('aaa');
})
});
}
var p2 = function() {
return new Promise(function (resolve){
console.log(new Date() + ' p2 赋值');
// setTimeout(() => {
// console.log(new Date() + ' resolve(bbb)');
// resolve('bbb');
// }, 2000);
timeOut(2000).then(function(){
console.log(new Date() + ' p2 timeOut赋值');
resolve('bbb');
})
});
}
var p3 = function() {
return new Promise(function (resolve){
console.log(new Date() + ' p3 赋值');
// setTimeout(() => {
// console.log(new Date() + ' resolve(ccc)');
// resolve('ccc');
// }, 1000);
timeOut(1000).then(function(){
console.log(new Date() + ' p3 timeOut赋值');
resolve('ccc');
})
});
}

var arr = [p1, p2, p3];
console.log(arr);
arr.reduce((p, f) => p.then((ret)=>{
console.log(new Date() + ret);
return f();
}), Promise.resolve()).then(result3 => { console.log(new Date() + result3); });

执行结果如下图: