一、题目:
实现mergePromise函数,把传进去的数组顺序先后执行,并且把返回的数据先后放到数组data中
//实现mergePromise函数,把传进去的数组顺序先后执行,
//并且把返回的数据先后放到数组data中
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 => {
// 在这里实现你的代码
};
// mergePromise([ajax1, ajax2, ajax3])
mergePromise([ajax1, ajax2, ajax3]).then(data => {
console.log('done');
console.log(data); // data 为 [1, 2, 3]
});
// 分别输出
// 1
// 2
// 3
// done
// [1, 2, 3]
二、参考答案:
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 data = [];
let prom = Promise.resolve();
ajaxArray.forEach(ajax => {
prom = prom.then(ajax).then(res => {
data.push(res);
return data;
});
})
return prom;
};
mergePromise([ajax1, ajax2, ajax3]).then(data => {
console.log('done');
console.log(data); // data 为 [1, 2, 3]
});
// 分别输出
// 1
// 2
// 3
// done
// [1, 2, 3]
三、题解:
答案可拆分为:
const mergePromise = ajaxArray => {
// 在这里实现你的代码
let data = []
let prom = Promise.resolve() // prom①
prom = prom // prom② = prom①.then()...
.then(ajaxArray[0])
.then(res => {
data.push(res)
return data
});
prom = prom // prom③ = prom②.then()...
.then(ajaxArray[1])
.then(res => {
data.push(res)
return data
});
prom = prom // prom④ = prom③.then()...
.then(ajaxArray[2])
.then(res => {
data.push(res)
return data
});
return prom // prom④
}
-
下一步的prom需等待上一步的prom运行完成,因为是链式调用,具体可看下面的继续拆分
上面的例子可继续拆分为:
const mergePromise = ajaxArray => {
// 在这里实现你的代码
let data = []
return Promise.resolve()
.then(ajaxArray[0])
.then(res => {
data.push(res)
return data
})
.then(ajaxArray[1])
.then(res => {
data.push(res)
return data
})
.then(ajaxArray[2])
.then(res => {
data.push(res)
return data
})
};
- 其实就是链式调用,then都会返回Promise对象
四、其他答案(async/await)
const mergePromise = ajaxArray => {
// 在这里实现你的代码
let data = []
let item
async function loop(){
while(ajaxArray.length){
item = await (ajaxArray.shift())()
data.push(item)
}
return data
}
return Promise.resolve(loop())
};