One problem encountered in the work
the for loop, and then out of the cycle and then a second request ID
This leads to a problem
Return order request result inconsistent
The reason: an asynchronous callback request will put micro-task event queue, the task is finished and then execute the macro micro tasks, with particular reference to the event queue mechanism
Solution:
Request by the map method is circulated
The method encapsulates asynchronous request, returns a promise
This will return an array having a plurality of promise
By promise.all () methods promise to promise packaged into a new instance
// 通过Promise把所有的异步请求放进事件队列中
getInfo(item ,index) {
const ms = 1000 * Math.ceil(Math.random() * 3)
return new Promise((resolve,reject) => {
setTimeout(() => {
axios.get(id).then((result) => {
resolve(result)
})
}, ms)
})
}
// 返回多个promise
let promise = arr.map((item,index) = > {
arr.forEach((item, index) => {
return getInfo(item, index)
})
})
// 对返回的promise数组进行操作
Peomise.all(promise).then((allData) => {
arr.forEach((item, index) => {
// ......
})
})