题目描述
实现mergePromise
函数,把传进去的数组按顺序先后执行,并且把返回的数据先后放到数据data里面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| const time = (timer) => { return new Promise(resolve => { setTimeout(() => { resolve(); }, timer); }) };
const ajax1 = () => time(2000).then(() => { console.log(1); return 1; })
const ajax2 = () => time(1000).then(() => { console.log(2); return 2; })
const ajax3 = () => time(1000).then(() => { console.log(3); return 3; })
function mergePromise(promises) {
}
mergePromise([ajax1, ajax2, ajax3]).then(data => { console.log('done'); console.log('data:', data); })
|
思路分析
这里要按照顺序执行,也就是执行1-2-3这样的顺序,但是1-2-3都用了setTimeout并且时间是不一致的,如果按照普通的思路,那么2-3会在1之前去执行,这样显然是不对的
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| function mergePromise(ajaxArray) { let data = []; let promise = Promise.resolve(); ajaxArray.forEach(ajax => { promise = promise.then(ajax).then(res => { data.push(res); return data; }) }); return promise; }
|