Axios 承诺返回未定义的数组

问题描述

在处理数据之前,我需要等待一系列 axios 调用(在 for 循环内)完成。所以我将它们添加一个承诺数组,然后使用 Promise.all()

static myFunction(games) {
  let promises = [];    
  games.forEach(game => {
    promises.push(this.getData(game));
  });

  Promise.all(promises)
    .then(gameData => {
    console.log("? promised:",gameData); //logging as [undefined,undefined,undefined]...
  })
}

static getData(game) {
  return axios({method: "get",url: urlStr})
   .then(res => {
     return parseHTMLData(res);
  }
}

static parseHTMLData(response) {
  return new Promise((resolve,reject) => {

    const $ = cheerio.load(response.data);
    const name = $(this).find('.team_name');
    return resolve(name);

  }
}

我已经确认我在 getData() 中成功取回了数据,但是在 Promise.all() 中,它以“未定义”数组的形式返回(当我在上面的代码中记录 gameData 时)。

知道为什么我的 axios 承诺返回 undefined 吗?

更新:问题是我正在使用 Cheerio 抓取从 Axios 检索到的数据,我需要将 Cheerio 抓取内容包装在 Promise 中。

解决方法

看看这个JSFiddle。这有效。也许解析数据有问题,因为没有拒绝,你得到了未定义的结果。

function myFunction(games) {
  let promises = [];    
  games.forEach(game => {
    promises.push(getData(game));
  });
  Promise.all(promises)
    .then(gameData => {
    console.log("? promised:",gameData); //logging as [undefined,undefined,undefined]...
  }).catch(err => console.log(err));
}

function getData(game) {
  return axios({
    method: "post",url: "/echo/html/",headers: {
      "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
    },data: `html=
<html>
    <body>
    <div class="team">
        <div class="team_name">${game.team_name}</div>
    </div>
  </body>
</html>`
  })
   .then(res => {
     return parseHTMLData(res);
  });
}

function parseHTMLData(response) {
  return new Promise((resolve,reject) => {
    const name = /class="(?:.*?)team_name(?:.*?)"(?:.*?)>(.*?)<\//g.exec(response.data);
    if (name.length > 1)
    {
        return resolve(name[1]);    
    }
    return reject("name not found");
  });
}

let games = [
    { team_name: "TEAM A" },{ team_name: "TEAM B" },{ team_name: "TEAM C" }
];

myFunction(games);