Home  >  Article  >  Web Front-end  >  Solve the problem of inconsistent order of asynchronous requests in for loop

Solve the problem of inconsistent order of asynchronous requests in for loop

angryTom
angryTomforward
2019-12-17 16:56:053000browse

Solve the problem of inconsistent order of asynchronous requests in for loop

Solving the problem of inconsistent asynchronous request order in the for loop

Encountered a problem at work

for loop, and then make a second request with the looped ID

This leads to a problem

The request result return order is inconsistent

Reason: Asynchronous requests will The callback event is put into the microtask event queue, and the microtask is executed after the macrotask is executed. For details, please refer to the event queue mechanism

[Related course recommendations: JavaScript video tutorial]

Solution:

Make a loop request through the map method

Encapsulate the asynchronous request method and return a promise

This will return an array with multiple promise

Wrap promise through the promise.all() method Into a new promise 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) => {
        // ......
    })
})

This article comes from the js tutorial column, welcome to learn!

The above is the detailed content of Solve the problem of inconsistent order of asynchronous requests in for loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete