zoukankan      html  css  js  c++  java
  • 解决for循环中异步请求顺序不一致的问题

    for循环,再把循环出来的ID再进行二次请求

    这就导致一个问题

    请求结果返回顺序不一致

    原因:异步请求会把回调事件放入微任务事件队列,宏任务执行完毕再执行微任务,具体参考事件队列机制

    解决方法:

    通过map方法进行循环请求

    将异步请求方法封装起来,返回一个promise

    这样将会返回一个具有多个promise的数组

    通过promise.all()方法把promise包装成一个新的promise实例

     1 // 通过Promise把所有的异步请求放进事件队列中
     2 
     3 getInfo(item ,index) {
     4 
     5     const ms = 1000 * Math.ceil(Math.random() * 3)
     6 
     7     return new Promise((resolve,reject) => {
     8 
     9         setTimeout(() => {
    10 
    11            axios.get(id).then((result) => {
    12 
    13                resolve(result)
    14 
    15            })
    16 
    17         }, ms)
    18 
    19     })
    20 
    21 }
    22 
    23  
    24 
    25 // 返回多个promise
    26 
    27 let promise = arr.map((item,index) = > {
    28 
    29     arr.forEach((item, index) => {
    30 
    31         return getInfo(item, index)
    32 
    33     })
    34 
    35 })
    36 
    37 // 对返回的promise数组进行操作
    38 
    39 Peomise.all(promise).then((allData) => {
    40 
    41     arr.forEach((item, index) => {
    42 
    43         // ......
    44 
    45     })
    46 
    47 })
  • 相关阅读:
    时间日期总览
    Mysql一次更新多条数据
    windows远程桌面连接无法粘贴
    vmware workstation pro密钥
    C#自动生成XML文件
    Mysql 缺少MSVCR120DLL问题
    hdu 5672 Strings 模拟
    poj 1328 雷达覆盖 贪心
    hdu 5667 Sequence (矩阵快速幂)
    CodeForces 652D Nested Segments 树状数组
  • 原文地址:https://www.cnblogs.com/mo3408/p/12210159.html
Copyright © 2011-2022 走看看