簡體   English   中英

在調用函數完成之前,異步/等待返回未定義

[英]Async/Await is returning undefined before the called function completes

我需要包裝我的函數playerLoop以便在teams每個players執行之后,它會做一些事情(當前將“成功”記錄到控制台。問題是我的包裝函數似乎忽略了await並繼續記錄“成功” “在playerLoop函數完成迭代之前。我是否在playerLoop缺少某些內容以將諾言返回給main()

我的playerLoop函數正在等待另一個函數( nbaFetch )的結果,然后進行一些計算,該部分工作正常。 只是似乎無法解決最后一點。

當前解決方案

 const main = async function () { try { var quote = await playerLoop(teams); console.log(quote); console.log('success'); } catch (error) { console.error(error); } } 

我也嘗試過

  async function main(){ let value = await playerLoop(teams); console.log(value); }; 

完整代碼如下:

 // Load in the right json object based on the player ID and calculate points async function nbaFetch(playerID){ let playerdashboardbygeneralsplits = await fetch('https://www.balldontlie.io/api/v1/stats?seasons[]=2018&per_page=100&player_ids[]=' + playerID + '&postseason=false', { mode: 'cors', method: "GET", headers: { "accept-encoding": "Accepflate, sdch", "accept-language": "he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4", "cache-control": "max-age=0", connection: "keep-alive", }, }) let nbaFileStruct = await playerdashboardbygeneralsplits.json() let game = nbaFileStruct.data // Loop through each game to grab each stat and push them into an array let assists = [] let points = [] let rebounds = [] let tov = [] let steals = [] let blocks = [] game.map(function(elem) { assists.push(elem.ast) points.push(elem.pts) rebounds.push(elem.reb) tov.push(elem.turnover) steals.push(elem.stl) blocks.push(elem.blk) }); // Reduce each array to its sum let sumPoints = points.reduce( (a, b) => { return a + b}, 0); let sumAssists = assists.reduce( (a, b) => { return a + b}, 0); let sumRebounds = rebounds.reduce( (a, b) => { return a + b}, 0); let sumSteals = steals.reduce( (a, b) => { return a + b}, 0); let sumBlocks = blocks.reduce( (a, b) => { return a + b}, 0); let sumTOV = tov.reduce( (a, b) => { return a + b}, 0); // Add the results and the custom multipliers to get a total points for each player let total = sumPoints + sumAssists*1.5 + sumRebounds*1.5 + sumSteals*2 + sumBlocks*2 - sumTOV*2 return total } // Team names and player IDs for each go here const teams = [ { name: 'Byron', players: ["192", "278", "176", "172", "37", "335"] }, { name: 'Moir', players: ["15", "447", "460", "405", "3", "79"] }, { name: 'Cail', players: ["137", "246", "349", "214", "200", "51"] }, { name: 'Boyd', players: ["417", "125", "228", "472", "132", "474"] }, { name: 'Mick', players: ["117", "274", "6", "387", "268", "210"] }, { name: 'Tex', players: ["140", "22", "169", "115", "322", "303"] }, { name: 'Trev', players: ["145", "189", "443", "434", "83", "318"] }, { name: 'Scott', players: ["237", "161", "465", "253", "315", "101"] } ]; // Loop over each of the teams & player IDs and push to our Output array const playerLoop = async function(teams) { await teams.map(function(team) { // Looping over the array of players should fill this array with results let output = [] Promise.all(team.players.map(async (playerID) => { let contents = await nbaFetch(playerID) output.push(contents) // Wait till all the iterations have completed and process the results })).then(function() { // Sort numerically and remove smallest number output.sort(function(a, b){return ba}); output.pop(); // Calculate sum of remaining numbers let sum = output.reduce( (a, b) => { return a + b}, 0); console.log(team.name, sum) // This will be moved once I work out how to return the result to main() return sum }, function(err) { // error occurred }); }); } // Trigger the function <- this is the part that isn't working const main = async function () { try { var quote = await playerLoop(teams); console.log(quote); console.log('success'); } catch (error) { console.error(error); } } main() 

你很親近

只是需要一個回報,另一個Promise.all和另一個回報-請參見下面代碼中標記為//********************注釋

 async function nbaFetch(playerID){ let playerdashboardbygeneralsplits = await fetch('https://www.balldontlie.io/api/v1/stats?seasons[]=2018&per_page=100&player_ids[]=' + playerID + '&postseason=false', { mode: 'cors', method: "GET", headers: { "accept-encoding": "Accepflate, sdch", "accept-language": "he-IL,he;q=0.8,en-US;q=0.6,en;q=0.4", "cache-control": "max-age=0", connection: "keep-alive", }, }) let nbaFileStruct = await playerdashboardbygeneralsplits.json() let game = nbaFileStruct.data // Loop through each game to grab each stat and push them into an array let assists = [] let points = [] let rebounds = [] let tov = [] let steals = [] let blocks = [] game.map(function(elem) { assists.push(elem.ast) points.push(elem.pts) rebounds.push(elem.reb) tov.push(elem.turnover) steals.push(elem.stl) blocks.push(elem.blk) }); // Reduce each array to its sum let sumPoints = points.reduce( (a, b) => { return a + b}, 0); let sumAssists = assists.reduce( (a, b) => { return a + b}, 0); let sumRebounds = rebounds.reduce( (a, b) => { return a + b}, 0); let sumSteals = steals.reduce( (a, b) => { return a + b}, 0); let sumBlocks = blocks.reduce( (a, b) => { return a + b}, 0); let sumTOV = tov.reduce( (a, b) => { return a + b}, 0); // Add the results and the custom multipliers to get a total points for each player let total = sumPoints + sumAssists*1.5 + sumRebounds*1.5 + sumSteals*2 + sumBlocks*2 - sumTOV*2 return total } // Team names and player IDs for each go here const teams = [ { name: 'Byron', players: ["192", "278", "176", "172", "37", "335"] }, { name: 'Moir', players: ["15", "447", "460", "405", "3", "79"] }, { name: 'Cail', players: ["137", "246", "349", "214", "200", "51"] }, { name: 'Boyd', players: ["417", "125", "228", "472", "132", "474"] }, { name: 'Mick', players: ["117", "274", "6", "387", "268", "210"] }, { name: 'Tex', players: ["140", "22", "169", "115", "322", "303"] }, { name: 'Trev', players: ["145", "189", "443", "434", "83", "318"] }, { name: 'Scott', players: ["237", "161", "465", "253", "315", "101"] } ]; // Loop over each of the teams & player IDs and push to our Output array const playerLoop = async function(teams) { // ***************************** // added return and Promise.all return await Promise.all(teams.map(function(team) { // Looping over the array of players should fill this array with results let output = [] // ***************************** // added return return Promise.all(team.players.map(async (playerID) => { let contents = await nbaFetch(playerID) output.push(contents) // Wait till all the iterations have completed and process the results })).then(function() { // Sort numerically and remove smallest number output.sort(function(a, b){return ba}); output.pop(); // Calculate sum of remaining numbers let sum = output.reduce( (a, b) => { return a + b}, 0); console.log(team.name, sum) // This will be moved once I work out how to return the result to main() return sum }, function(err) { // error occurred }); })); } // Trigger the function <- this is the part that isn't working const main = async function () { try { var quote = await playerLoop(teams); console.log(quote); console.log('success'); } catch (error) { console.error(error); } } main() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM