1. 介绍
在web实际开发中,也许会用到多个异步操作按顺序执行完成。比如有5个ajax请求,希望前面一个ajax请求完成后,再执行后面一个请求,5个ajax依次请求完成。
2. Promise执行链
说明:使用Array.reduce()方法,让多个Promise函数依次执行。
示例:
let p1 = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('one'); resolve() }, 1400); }) }; let p2 = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('two'); resolve() }, 1300); }) }; let p3 = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('three'); resolve() }, 1200); }) }; let p4 = () => { return new Promise((resolve, reject) => { setTimeout(() => { console.log('four'); resolve() }, 1100); }) }; // reduce 依次执行 [p1, p2, p3, p4].reduce((p, fn) => { return p.then(fn) }, Promise.resolve());
输出结果: