实现串行方式请求接口示例
代码片段:https://developers.weixin.qq.com/s/QPAGZSm67Lug
注意代码中 , 串行跟并行代码实现中,遇到的最明显区别在于, for 循环跟 forEach 循环的区别。也期望能收到解释for 循环跟 forEach 循环的区别相关解答
MockAjaxLayer(time) {
return new Promise((resolve, reject) => {
// wx.request({
// url: `http://localhost:3001/data1?time=${time}`,
// success(res) {
// setTimeout(()=>{
// resolve(res);
// },2000)
// },
// fail(err) {
// reject(err);
// }
// })
setTimeout(() => {
resolve(time);
}, 1500);
})
},
serialExample() {
var self = this
let time = +new Date()
let promises = []; // 初始化promise数组
for (let i = 0; i < 10; i++) {
promises.push(
() => self.MockAjaxLayer(i)
);
}
// // 利用async/await进行串行操作
async function asyncFn(promises) {
for (let i = 0; i < promises.length; i++) {
let res = await promises[i]();
console.log(res)
}
}
asyncFn(promises);
},
parallelExample() {
var self = this
let time = +new Date()
let promises = []; // 初始化promise数组
for (let i = 0; i < 5; i++) {
promises.push(
() => self.MockAjaxLayer(i)
);
}
async function asyncFn(promises) {
promises.forEach(async promise => {
let res = await promise();
console.log("parallelExample res", res)
});
}
asyncFn(promises);
}