【问题标题】:Why does my promise return an array of [object] or [array]为什么我的承诺返回一个 [object] 或 [array] 数组
【发布时间】:2019-04-27 04:39:57
【问题描述】:

我正在尝试遍历来自 github 的 api 的 url 列表,并返回一个包含所有信息的数组。我返回的是一个带有 [object],[object] 而不是实际数据的数组。我认为这与我的承诺没有解决有关。

这是我的功能:

async function getCommitsByWeek() {
  const allRepoNames = await getRepos(user);
  const repoURLs = await allRepoNames.map(({ full_name, name }) => {
    return {
      name,
      url: `https://api.github.com/repos/${full_name}/stats/contributors`,
    };
  });

  const theStuff = await Promise.all(
    repoURLs.map(({ url, name }) =>
      axios.get(url, AUTH).then(({ data }) => {
        const info = data[0].weeks.map(week => {
          return { w: week.w, c: week.c };
        });
        //console.log(name, info);
        return { name, info };
      })
    )
  );
  return theStuff
}

这是预期的

{ name: 'my-github-data_frontend',
  info: [ { w: 1555804800, c: 1 } ] }
{ name: 'Below-the-fold',
  info:
   [ { w: 1542499200, c: 2 },
     { w: 1543104000, c: 0 },
     { w: 1555200000, c: 0 },
     { w: 1555804800, c: 0 } ] }
{ name: 'contraction-app',
  info:
   [ { w: 1536451200, c: 9 },
     { w: 1537056000, c: 5 },
     { w: 1555200000, c: 0 },
     { w: 1555804800, c: 0 } ] }


这就是我目前得到的

{ name: 'Below-the-fold',
    info:
     [ [Object],
       [Object],
       [Object], ] },
  { name: 'contraction-app',
    info:
     [ [Object],
       [Object],
       [Object],
       [Object],

【问题讨论】:

  • 控制台就是这样显示的。将其输出为 JSON 以确定它是什么。
  • 尼特:没有理由await allRepoNames.map 这不是一个承诺。其他 nit:在任何地方使用 async/await - 你可以用它替换 .then

标签: javascript node.js promise async-await


【解决方案1】:

这就是控制台的显示方式。在您的“我所期待的”中,您举了一个对象数组的示例。

控制台输出显示了一个对象数组,但没有给出每个对象的详细信息。

如果您想强制控制台显示每个 info 对象中的内容,您可以使用 console.log(name, JSON.stringify(info));

顺便说一句,您的代码末尾附近的return theStuff 看起来不合适。不知道这是在做什么。

【讨论】:

  • nodejs 控制台不是交互式的。
  • @JonasWilms 我没有注意到 node.js 标签。感谢您指出了这一点。我已经基于此编辑了我的答案。
猜你喜欢
  • 2017-06-19
  • 2016-09-30
  • 1970-01-01
  • 2015-11-27
相关资源
最近更新 更多