Manveer
Manveer

Reputation: 23

Function does not wait until Promise is resolved

I'm developing a simple discord bot and I am attempting to print some general data about a certain player. I recently learned about async/await and I attempted to implement it into my code. It does not seem to work however because when I first trigger this code, it prints null but on subsequent triggers it will print the correct data, indicating that my function did not wait for the Promise to resolve.

async function stats(){
    data = await NBA.stats.playerInfo({ PlayerID: curry.playerId });
}

 stats();  

 data = JSON.stringify(data);
 console.log(data);

The variable data is a global variable declared at the top of my program and initially initialized to null.

Upvotes: 2

Views: 6067

Answers (1)

Aakash Jain
Aakash Jain

Reputation: 1973

If I understand your intention correctly, what you want is to asynchronously fetch some data into data and then display it on the console.

Your implementation of stats is doing the fetch correctly. But your problem is, the part where you log to console has no dependence on the fetch being completed.

When you call a function that has been declared async, you are saying that you want it to execute "in the background" so to speak. The interpreter won't wait for that function to finish executing.

stats(); // begin executing this function

data = JSON.stringify(data); // but don't wait for it to finish before moving on to this line
console.log(data);

Clearly, that's not what you want. Instead, you want to wait for stats to finish what it's doing before logging data. stats being an async function returns a Promise, so you can do this:

function logData() {
  console.log(JSON.stringify(data));
}

stats().then(logData);

Upvotes: 6

Related Questions