【发布时间】:2019-06-22 23:08:52
【问题描述】:
我正在构建一个聊天机器人,它从聊天中获取消息,并将其发送到一个 api,该 api 根据该消息生成一个随机 gif。
axios 请求/响应正常工作,但我需要它将响应中的 URL 值存储为外部变量。
然后变量/URL 将使用另一个函数在聊天中发送。该函数不能在 axios request/then 语句中运行,而且我似乎也无法从内部获取要更新的变量。
我对此有点困惑,还没有找到一种方法可以满足我的需要。任何建议表示赞赏。
How do I return the response from an asynchronous call? 没有说明如何从外部获取此信息,因为我无法从 then 语句内部运行消息函数。
const sentence = context.activity.text.replace('!guggy ', '');
//theoretically this would hold the api response, but this wont update as intended
//var apiResponse;
//api call function
function postRequest(x) {
return axios.post('http://exampleurl.here.com/helpapi', {
"sentence" : x,
"lang": "ru"
},{
headers: {
"Content-Type":"application/json",
"apiKey":"example-key-2020202"
}
});
}
//initiates api call, then logs response or error
postRequest(sentence).then(function(response) {
console.log(response.data.animated[0].gif.original.url); //this works, returns URL
//attempting to store the same value as external variable doesnt work
apiResponse = response.data.animated[0].gif.original.url; //the variable remains blank when called later
}).catch (function (error) {
console.log(error);
});
//this has to be run outside of axios/then statement, or it will not work.
//this should take the url passed from the response, and send it as a chat message
await context.sendActivity(apiResponse);
这实际上不会返回任何错误,而是在服务器上运行。当我需要它时它只是不返回变量 - 它是空白的。我假设这意味着我只是忽略或误解了一些重要的事情。
【问题讨论】:
-
您不能同步使用异步检索的值。您必须在 Promise 上调用
.then来使用它(或使用await),然后在.then中执行依赖它的所有操作 -
我不确定你所说的另一个问题是不是骗人的——它正是是你遇到的问题。这就是异步编程的本质。它甚至为您提供多种解决方案,例如等待。那不适合你怎么办?
标签: node.js post axios response