Promise数组顺序执行

function sequenceTasks(tasks) {
function recordValue(results, value) {
results.push(value);
return results;
}
var pushValue = recordValue.bind(null, []);
return tasks.reduce(function (promise, task) {
return promise.then(task).then(pushValue);
}, Promise.resolve());
}
function taskA() {
console.log("Task A");
return "TaskA";
}
function taskB() {
console.log("Task B");
return "TaskB";
}
function finalTask() {
console.log("Final Task");
return "Final Task";
}
function main() {
return sequenceTasks([taskA, taskB, finalTask]);
}
// 运行示例
main().then(function (value) {
console.log(value);
}).catch(function(error){
console.error(error);
});
运行结果:
Task A
Task B
Final Task
TaskA,TaskB,Final Task

你可能感兴趣的:(Promise数组顺序执行)