简体   繁体   中英

Async/Await functions

I'm trying to pull the data from a url, but am unsure as to what I'm doing wrong. When I console.log the returned result.data, I get a Promise, but when I console.log result.data inside of my function, I get all of the data. Here is my code:

async function getTeams() {
    const result = await axios({
        method: "get",
        url: 'http://api.sportradar.us/ncaafb-t1/teams/FBS/2018/REG/standings.json?api_key=sg8pf7bdjt5u8ueedttyytwx',
    });
    console.log(result.data);
    return result.data;
}
console.log(getTeams());

I'm not sure what I should be doing differently to get a completed promise.

EDIT: I needed to use a getTeams().then() with callbacks to work better. However, now I am running into an issue of storing the data inside the.then() that I can access into global variables. My code now looks like:

async function getTeams() {
    const result = await axios({
        method: "get",
        url: 'http://api.sportradar.us/ncaafb-t1/teams/FBS/2018/REG/standings.json?api_key=sg8pf7bdjt5u8ueedttyytwx',
    });
    return result.data;
}
let teams = [];
getTeams().then(data => {
    let acc = data.division.conferences[0];
    for (let i = 0; i < acc.teams.length; i++) {
        teams.push(acc.teams[i]);
    }
})

Async functions always return a promise. At the time you log the return value, the async operation is not yet complete -- control must return to the JavaScript main loop before the async operation can continue.

You must await the returned promise:

getTeams().then(console.log.bind(console));

The solution to my question with respect to Promises is to restructure my code such that the code that needs the Promise's response is done inside the Promise. You can nest a function inside the Promise, change state (if using something like React) inside a Promise that gets executed later, or a variety of other things.

getTeams.then(teams => {
    // Print out each team
    for (let i = 0; i < teams.length; i++) {
         console.log(teams[i]);
    }

    // Set state (in React)
    setTeams(teams);

    // Do other stuff with teams
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM