对不起,我英语不好.但是我遇到了一个问题,我希望有人能帮我解决.

const FinalResult = [];

const users = [
  {
    short: "gurdt",
    gameTag: "gurdt#3199278"
  },
  {
    short: "lc",
    gameTag: "LC_92#4607792"
  },
  {
    short: "ray",
    gameTag: "The_Green_Ray"
  },
  {
    short: "leon",
    gameTag: "Theaxeman777#7613572"
  }
];

async function getData(user) {
  const config = {
    method: "get",
    url: `https://my.callofduty.com/api/papi-client/stats/cod/v1/title/mw/platform/uno/gamer/${encodeURIComponent(
      user
    )}/profile/type/wz`,
    headers: {
      Cookie:
        "TOKEN-1234"
    }
  };

  const rawResponse = await axios(config);
  const result = {
    user: user,
    ...rawResponse.data.data.weekly.all.properties
  };

  return result;
}

users.map((user) => {
  const data = getData(user.gameTag);

  FinalResult.push(data);
  return false;
});

console.log(FinalResult);

我想要的是,他在users上循环,在这里生成一个包含所有结果FinalResult的大array.

希望你知道我的意思,否则明天我会更新这个问题,因为我在我的电脑上,并把更多的信息..

推荐答案

Map每个users个条目对应一个promise ,该promise 将与您想要的数据进行解析.将这个promise 数组传递给Promise.all(),以创建一个您可以等待的promise .

// this will make for cleaner code
const gamerApi = axios.create({
  baseURL:
    "https://my.callofduty.com/api/papi-client/stats/cod/v1/title/mw/platform/uno/gamer/",
  headers: {
    Cookie: "TOKEN-1234;",
  },
});

const promises = users.map(async (user) => {
  const { data } = await gamerApi.get(
    `${encodeURIComponent(user.gameTag)}/profile/type/wz`
  );
  return {
    user,
    ...data.data.weekly.all.properties,
  };
});

// If you're currently in an async function...
const finalResult = await Promise.all(promises);

// otherwise, use .then()...
Promise.all(promises).then((finalResult) => {
  // use finalResult here
});

结果将是一个具有user个属性的对象数组,该属性与响应中的任何内容合并.

Node.js相关问答推荐

promise 所有映射或反对

MongoDB-如何验证Document字段以仅允许特定的文件扩展名?

如何在Sequelize with Postgres中将m:n关联表ID从整数迁移到UUID?

如何在医学中按patientId查找一个并同时插入多个数据

mongodb首先自连接,然后根据某些条件与另一个表连接

如何在 Firestore 函数上使用类型模型来获取字段值

如何通过node下载zip并直接解压zip?

为什么后端开发需要单独的服务器?

在 Express.js 中迭代子文档数组

使用 Node.js 在 MongoDB 中搜索

NodeJS 后端发布请求将数据作为NULL值发布到 SQL Server 表

Winston http 日志(log)级别的行为与 info 不同

Node.js 中空函数的简写

如何在 NodeJs 中下载和解压缩内存中的 zip 文件?

代理(如提琴手)可以与 Node.js 的 ClientRequest 一起使用吗

安装Node.js 安装n 安装Node.js?

Meteor - collection.find() 总是返回所有字段

Node.js 连接仅适用于本地主机

如何设置 useMongoClient (Mongoose 4.11.0)?

什么时候应该将函数存储到变量中?