js循环调用接口循环最后一次保存全部数据

const tList = ['id:123', 'id:46', 'id:83'];
const resObj = {};
const state = [];
resultList.forEach((item, index) => {
    接口({ data: item }).then((res) => {
        resObj[item] = res.data;
        if(index === resultList.length - 1) {
            state = resObj;
        }
    })
})

有什么好的方法吗?循环中 index 的值并不是 0 1 2 3

阅读 4k
3 个回答

给出的信息没有 resultList 的结构,但从代码来看 item 应该是一个字符串,而不是一个数组,所以 index === item.length - 1 这个条件可能存在逻辑失误。

Promise.all

Promise.all(resultList.map(item => 接口({ data: item })))
    .then(result => state = result.map(({ data }) => data));

再用上 await

(async () => {
    state = await Promise.all(...);
})();
let i=0;
resultList.forEach((item, index) => {
    接口({ data: item }).then((res) => {
        resObj[item] = res.data;
        if(i === item.length - 1) {
            state = resObj;
        }
        if(i < item.length - 1) {
            i++
        }
    })
})

推荐promise.all,更简洁

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题