Home > Web Front-end > JS Tutorial > 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
Release: 2019-12-17 16:56:05
forward
3020 people have browsed it

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) => {
        // ......
    })
})
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template