javascript - Async/Await 在被调用函数完成之前返回未定义

标签 javascript async-await

我想包装我的函数playerLoop,以便在它对teams中的每个players执行后,它会做一些事情(目前将“成功”记录到控制台。问题是我的包装函数似乎忽略了 await 并在 playerLoop 函数完成其迭代之前继续记录“成功”。我错过了吗playerLoop 中的某些内容向 main() 返回 promise ?

我的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 b-a});
            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 b-a});
            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()

关于javascript - Async/Await 在被调用函数完成之前返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604596/

相关文章:

没有 jQuery 的 javascript xhr 文件上传

javascript - 我如何使用 jQuery 从 <head> 读取所有 &lt;meta..>?

c# - 在 .net 4.5 中努力尝试使 cookie 无法响应 HttpClient

JavaScript:单击按钮时无法更改 div 的背景颜色

javascript - 带滚动的视差和振动背景图像

javascript - 从 Javascript 响应对象中提取 YQL 查询内容

javascript - 在异步函数中使用await关键字与省略它有什么区别?

javascript - Node 异步/等待与 promise.all

c# - 使用异步 CTP 同时下载 HTML 页面

c# - 如果我们同步等待结果,使用任务有什么好处吗?