使用axios返回数据时,在推入数组时会导致异步问题

时间:2019-05-16 12:11:22

标签: reactjs ecmascript-6 promise async-await axios

我试图从一些API中获取一些信息,并在数组上循环以从axios获取结果数组,但该信息未正确推送到resultat数组,我认为这是一个异步问题,因为当我在调用该组件的setTimeout中数组,它正确显示数据,当不使用setTimeout时,它正确显示数组,但无法访问其值 您能否帮我实现使信息异步的功能或给我另一个解决方案

问题是由foreach循环引起的,也许诺言可以解决问题 代码是

const orgName = org.value.substr(1);
  const groups = user.group.filter(group => group.includes(orgName));
  const resultat = [];
  dispatch(SharingLoading());
  groups.forEach(function(group, index) {
    let idparts = group.split("#");
    let aBox = "a" + orgName;
    axios
      .get("api/" + aBox + "/group/" + aBox + ":" + idparts[1])
      .then(res => resultat.push(res.data[0]));
  });
  dispatch(setSharing(resultat)); 

2 个答案:

答案 0 :(得分:0)

const orgName = org.value.substr(1);
const groups = user.group.filter(group => group.includes(orgName));
let resultat = [];
dispatch(SharingLoading());

groups.forEach(function (group, index) {
    let idparts = group.split("#");
    let aBox = "a" + orgName;
    let data = await collectData(aBox, idparts[1])
    resultat.push(data)
});

var collectData = (aBox, idparts) => new Promise((resolve, reject) => {
    axios
        .get("api/" + aBox + "/group/" + aBox + ":" + idparts)
        .then(res => resolve(res.data[0]))
        .catch(err => reject(err))
})
dispatch(setSharing(resultat));

答案 1 :(得分:0)

const orgName = org.value.substr(1);
const groups = user.group.filter(group => group.includes(orgName));
dispatch(SharingLoading());
Promise.all(groups.map(group => {
  let idparts = group.split("#");
  let aBox = "a" + orgName;
  return axios
    .get("api/" + aBox + "/group/" + aBox + ":" + idparts[1])
})).then(list => list.map(res => res.data[0]))
.then(resultat => dispatch(setSharing(resultat)));