【问题标题】:How do I save the axios response to variable, to be used outside axios? [duplicate]如何将 axios 响应保存到变量,以便在 axios 外部使用? [复制]
【发布时间】: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


【解决方案1】:

代码sn-p中的执行顺序为:

  1. 调用 axios
  2. axios 通过网络发送消息。
  3. context.sendActivity() 以空白 apiResponse 调用。
  4. exampleurl.here.com 向 axios 返回答案。
  5. axios 调用“then”子句。
  6. 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2021-09-13
    • 2022-06-27
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多