如何等待带有API调用的for循环的最终结果



这个循环将运行任意次数,我想从中得到结果。我尝试的任何东西(promising、async/await、嵌套函数等(似乎都是死胡同。我不明白为什么我不能在API调用或我在这里创建的函数上粘贴.then。但我怀疑这个问题在我的理解中更为根本,因为我似乎甚至无法理解";数据";返回。。。无法等待API调用。把它包装在承诺中会失去";数据";并用";对于循环";里面也不起作用。这让我质疑我在JS/实现他人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循环完成后得到结果。";循环;我指的是";对于";在数据对象上。"将代码放在循环之后但放在回调内部";不起作用。在我之前的一周里,我有一个问题没有解决:如何在Javascript中解决种族问题?以下是全部内容,并对过去的一些版本进行了评论

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()
}}

您可以让这个函数返回一个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
}
})();

相关内容

  • 没有找到相关文章

最新更新