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

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相关问答推荐

无法验证叶签名|无法验证第一个证书

node 模块错误:类型参数OT具有循环约束''

如何在RavenDB中执行JS索引?

关于Node.js中的AES加密库的问题

为什么即使数据库确实更新了,此 POST 也无法解析并返回 200 代码?

NPM如何管理node_modules传递依赖?

运行本地移动自动化测试时,在onPrepare钩子中,ERROR @wdio/cli:utils: A service failed in the 'onPrepare'

在 Nest 项目上运行 Jest 测试时,我的文件无法找到一个在测试之外没有任何问题的模块

当try 将 formData 转换为 express js 时,服务器无法识别 multipart/form-data

我应该转译我的 TypeScript 应用程序吗?

是Electron 的密码和登录凭据的安全存储吗?

使用 firebase 函数 api 运行套接字(相同的端口创建问题)

Firestore promise 在退货前等待产品详细信息

在 Passport 策略回调中获取请求对象

file.slim.js 中的苗条是什么

Node.js, require.main === 模块

Passport 的 req.isAuthenticated 总是返回 false,即使我硬编码 done(null, true)

如何从 findOneAndUpdate 方法中获取更新的文档?

当我try 向我的 S3 存储桶 (Node.js) 发送内容时,AWS 缺少凭证

mongoose 填充与对象嵌套