如何使用 API 调用等待 for 循环的最终结果?

How to wait for the final result of a for loop with API calls?

这个循环将进行 运行 任意次数,我想在所有循环之后得到结果。我尝试的任何事情(承诺、async/await、嵌套函数等)似乎都是死胡同。我不明白为什么我不能只在 API 调用或我在此处创建的函数上添加 .then。但我怀疑这个问题在我的理解中更为根本,因为我似乎甚至无法获得 return 的“数据”......同样无法等待 API 调用。将它包装在一个承诺中会丢失“数据”并在其中使用“for 循环”将其拉出也不起作用。这让我质疑我与 JS/implementing 其他人的 API 的整个进步。

  const gotPeeps = () => {
      challongeClient.tournaments.show({
      id: tournamentURL,
      callback: (err, data) => {
         //return data //doesnt return "data" from gotPeeps?
        for (const [key, value] of Object.entries(data.tournament.matches)) {
            if (value.match.state === 'open') {
              peepsList.push(value.match.player1Id, value.match.player2Id)
              console.log(peepsList)
    }}}})}
    gotPeeps()

编辑 对评论: 我试图在 for 循环完成后得到结果。 我指的“循环”是数据对象上的“for of”。 “将代码放在循环之后但在回调内部”不起作用。在我未能解决此问题的一周中,我有一个先前的问题: 这是全部内容,一些过去的版本被注释掉了。:

const tournamentModel = require('../models/tournamentSchema')
require('dotenv').config()
const challonge = require('challonge');

module.exports = {
  name: 'getmatches',
  aliases: ['gm'],
  cooldown: 0,
  description: 'Get Challonge data into console.',
 
  execute(message, args, cmd, client, Discord, profileData) {
    let peep = ''
    let peepsList = ''
    const tournamentURL = 'TESTING_Just_Sign_Up_If_You_See_This850587786533011496'
    const challongeClient = challonge.createClient({
      apiKey: process.env.CHALLONGE_API_KEY,
    })
  
  const getPlayer = (playerXId) => {
    return new Promise((resolve, reject) => {
      challongeClient.participants.show({
        id: tournamentURL,
        participantId: playerXId,
        callback: (err, data) => {
          if (err) {
            reject(err);
            return;
          }        
          peep = data.participant.misc
          peepsList.push(peep)
          console.log(peepsList)
          console.log('RUNNING GET PLAYER', playerXId, playerIndexCount)
          resolve(peepsList);  
          }
        });
      });
    }
    
    

    const peepsList = []
    const matchList = []
    const gotPeeps = () => {
      challongeClient.tournaments.show({
      id: tournamentURL,
      include_participants: 1,
      include_matches: 1,
      callback: (err, data) => {
        for (const [key, value] of Object.entries(data.tournament.matches)) {
            if (value.match.state === 'open') {
              peepsList.push(value.match.player1Id, value.match.player2Id)
              console.log(peepsList)
            }
          }
      }
        
              /*// GET PLAYERS
            getPlayer(value.match.player1Id)
            .then(() => {
            getPlayer(value.match.player2Id)
          }) 
        }
          */
                    
                  }
            )         
      }
      
    gotPeeps()
    }}

您可以使此函数 return 成为一个 promise 并等待该函数(只要您的函数是 async 函数)

const gotPeeps = () => {
  return new Promise((resolve, reject) => {
    const peepsList = []; // declare the empty array to e filled

    challongeClient.tournaments.show({
      id: tournamentURL,
      callback: (err, data) => {
        for (const [key, value] of Object.entries(data.tournament.matches)) {
          if (value.match.state === "open") {
            peepsList.push(value.match.player1Id, value.match.player2Id);
          }
        }
        resolve(peepsList); // resolve the promise with the filled array
        // TODO: handle reject
      },
    });
  })
};

(async () => {
  try {
    const result = await gotPeeps();
  } catch (error) {
    // TODO: handle error
  }
})();