V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
OkabeRintaro
V2EX  ›  前端开发

小白问题] axios 循环请求,响应时间不同,导致数据的排序紊乱

  •  
  •   OkabeRintaro · 2022-04-27 18:17:11 +08:00 · 1063 次点击
    这是一个创建于 722 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在用 VUE 仿写一款小说阅读器,在根据 ID 发送 axios 请求获取小说内容数据的时候,渲染到页面的时候,顺序出现了问题. 用 forEach 遍历这个数组,然后去请求数据,但是每章小说的内容不一样,获取到的时间也不一样,导致章节紊乱......

    arr: [ { id: "111x" },/* 对应的数据是小说的第一章, 至少 2 秒才响应返回数据*/ { id: "222xs" },/* 对应的数据是小说的第二章 至少 5 秒才响应返回数据*/ { id: "333sa" },/* 对应的数据是小说的第三章 至少 3 秒才响应返回数据*/ ... ] ,根据数组 arr 的每个对象的属性 ID 作为参数,循环 axios 请求来获取数据,存入数组, 要求: 最终该数组的数据排序应该是小说的第一章,第二章,第三章......即数据需要按照对象的索引排序

    呜呜,来个大佬帮一下...... 问题

    5 条回复    2022-04-28 07:50:25 +08:00
    noe132
        1
    noe132  
       2022-04-27 18:24:28 +08:00 via Android
    学习一下 Promise 把小老弟
    看看 Promise.all
    YuxiangLuo
        2
    YuxiangLuo  
       2022-04-27 18:30:41 +08:00
    let id_arr = [
    {
    id: "001"
    },
    {
    id: "002"
    },
    {
    id: "003"
    },
    {
    id: "004"
    }
    ]

    let content_arr = new Array(id_arr.length);


    id_arr.forEach(async (id, index) => {
    console.log(id, index);
    let res = await axios.get("https://getcontent.com/"+id.id);
    let content = res.data;
    content_arr[index] = content;
    })

    setTimeout(() => {
    console.log(content_arr);
    }, 10000);
    OkabeRintaro
        3
    OkabeRintaro  
    OP
       2022-04-27 19:40:43 +08:00
    @YuxiangLuo @noe132 谢谢! 用了 axios.all()和 axios.spread()已经拍好了 先循环弄出所有的 promise 对象放入新数组,再 all 这个新数组 ,spread 出来所有的正确顺序
    OkabeRintaro
        4
    OkabeRintaro  
    OP
       2022-04-27 19:48:17 +08:00
    <script>
    import axios from "axios";
    created() {
    //第一次进小说,只要前 4 章
    this.firstSecIdList = (this.bookList || "").slice(0, 4);
    // 遍历前四个,四个全部分到一个新的 url 数组集合里
    this.firstSecIdList.forEach((item, index) => {
    // 请求章节内容的 URL 链接
    item, index;
    this.firstSecIdListURl.push(
    axios.get(
    `A----P----I?小说内容 ID=${item.secId}`
    )
    );
    });
    // 输出这 4 个 promise 对象
    console.log(this.firstSecIdListURl);

    axios.all(this.firstSecIdListURl).then(
    axios.spread((...res) => {
    // 由于不知道数组的长度,所以我们通过...扩展运算符将数组变成一个参数序列
    [...res].forEach((item, index) => {
    index;
    console.log(item, index);//输出结果为按照索引发出的请求并且是正确的顺序的返回数据
    //小说内容放进页面
    this.bookContent = item.data.data.content;
    this.$refs.content.innerHTML += this.bookContent;
    });
    })
    );
    });
    </script>
    elboble
        5
    elboble  
       2022-04-28 07:50:25 +08:00 via Android
    axios 是异步的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5731 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:56 · PVG 09:56 · LAX 18:56 · JFK 21:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.