Node.js 如何将axios响应保存到变量,以便在axios外部使用?
我正在构建一个聊天机器人,它从聊天中获取一条消息,并将其发送到一个api,该api根据消息生成一个随机gif axios请求/响应工作正常,但我需要它将响应中的URL值存储为外部变量 然后使用另一个函数在聊天中发送变量/URL。这个函数不能在axios request/then语句中运行,而且我似乎也不能从内部获取要更新的变量 我有点被困在这一点上,还没有找到一种方法来做我需要的事情。任何建议都将不胜感激 没有说明如何从外部获取此消息,因为我无法从then语句内部运行消息函数Node.js 如何将axios响应保存到变量,以便在axios外部使用?,node.js,post,axios,response,Node.js,Post,Axios,Response,我正在构建一个聊天机器人,它从聊天中获取一条消息,并将其发送到一个api,该api根据消息生成一个随机gif axios请求/响应工作正常,但我需要它将响应中的URL值存储为外部变量 然后使用另一个函数在聊天中发送变量/URL。这个函数不能在axios request/then语句中运行,而且我似乎也不能从内部获取要更新的变量 我有点被困在这一点上,还没有找到一种方法来做我需要的事情。任何建议都将不胜感激 没有说明如何从外部获取此消息,因为我无法从then语句内部运行消息函数 const sen
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);
这实际上不会返回任何错误,而是在服务器上运行。它只是在我需要它时不返回变量-它是空的。我假设这意味着我忽略了或误解了一些重要的事情。代码片段中的执行顺序是:
context.sendActivity()
时使用空白apiResponse
apiResponse
已分配const sentence = context.activity.text.replace('!guggy ', '');
async function postRequest(x) {
return await axios.post('http://exampleurl.here.com/helpapi', {
"sentence" : x,
"lang": "ru"
},{
headers: {
"Content-Type":"application/json",
"apiKey":"example-key-2020202"
}
});
}
try {
const response = await postRequest(sentence);
} catch (error) {
console.log(error);
}
console.log(response.data.animated[0].gif.original.url);
apiResponse = response.data.animated[0].gif.original.url;
await context.sendActivity(apiResponse);
无法同步使用异步检索的值。你必须打电话给
。然后
承诺使用它(或者使用等待
),然后在中做一切依赖它的事情。然后
我不确定你说的另一个问题是什么意思,这不是一个骗局——这正是你面临的问题。这就是异步编程的本质。它甚至为您提供多种解决方案,如等待。那对你不起作用的呢?