js中for循环多次请求,返回数据不按照顺序返回的处理

参考: https://www.cnblogs.com/taxun/p/13686719.html

// 获取房间号
let roomalls = []
for (let i = 0; i < res.data.room_device_relations.length; i++) {
    roomalls.push(getrom(res.data.room_device_relations[i].room_id))    //  返回的是 [Promise] 数组
}
console.log(roomalls)
Promise.all(roomalls).then(res => {
    console.log(res)
    setRoomalls(res)
})
  // 可以用  async   await  变同步的方法
    const getrom = async (val) => {
        const msg = await roomsthing(val)
        console.log(msg)
        return msg.data.room_no
    }

  业务场景    在   一个请求回来的数据中有个数组  多项 的id      要用这些  id   在   去依次请求 接口    就需要先在循环中 用数组 保存 每一个 promers  然后 在用 promise.all 在  把结果 列出来

原文地址:https://www.cnblogs.com/thlcom/p/15044667.html