Function does not wait until Promise is resolved

余生长醉 提交于 2020-01-06 07:53:08

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/55348886/function-does-not-wait-until-promise-is-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!