函数不会等到Promise解决之后 [英] Function does not wait until Promise is resolved

查看:78
本文介绍了函数不会等到Promise解决之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的Discord机器人,并且尝试打印有关某个玩家的一些常规数据.我最近了解了异步/等待,并尝试将其实现到我的代码中.但是,它似乎不起作用,因为当我第一次触发此代码时,它会输出null,但是在后续触发时它将输出正确的数据,这表明我的函数没有等待Promise解析.

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

变量数据是在程序顶部声明的全局变量,最初被初始化为null.

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

推荐答案

如果我正确理解了您的意图,那么您想要的是异步地将某些数据提取到data中,然后在控制台上显示它们.

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

您的stats实现正确完成了提取.但是您的问题是,您登录到控制台的部分不依赖于完成的提取.

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.

当您调用已声明为async的函数时,就是说您希望该函数在后台"执行.解释器不会等待该函数完成执行.

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

很明显,这不是您想要的.相反,您要等待stats完成它的操作,然后再记录data. stats作为异步函数会返回Promise,因此您可以执行以下操作:

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

这篇关于函数不会等到Promise解决之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆