【问题标题】:Await and .then not getting Axios Promise等待然后 .then 没有得到 Axios Promise
【发布时间】:2021-08-03 03:42:39
【问题描述】:

我正在通过我正在构建的应用程序跟踪我的方式。我已经对步骤进行了编号,以确定什么是被调用的,什么不是。

我调用 Axios 并尝试调用 .then() 从返回的 Promise 中获取数据,但它从未执行。应用程序继续运行:

module.exports = async function request(requestOpts = {}) {
  console.log("5: in request... sending request")
  const response = await sendRequest({
    method: requestOpts.method,
    url: requestOpts.url,
    headers: requestOpts.headers,
  }).then(function(response) {
    console.log("7: in request.. returning response")
    return response;
  })
  

};

function sendRequest(requestOpts = {}) {
  console.log("6: in sendRequest.. returning axios")
  return (
    axios({
      method: requestOpts.method,
      url: requestOpts.url,
      headers: requestOpts.headers,
    }).then((response) => {
      console.log("Then ===> " + response)
      return response;
    }).catch((error) => {
      console.log("Error ==> " + error)
      return error;
    })
    );
}

第 7 步永远不会出现......事情只是继续前进并完成。我是否正确设置了此设置?这是调用模块:

module.exports = async function axiosCaller() {
    console.log('4: in axiosCaller')
    const authHeader = buildBasicAuth();
    let response = await request({
        url: 'redacted',
        method: 'get',
        headers: {
            authHeader
        },
    }).then((response) => {
        console.log(response);
    return handleResponse(response);
      });
    }

【问题讨论】:

    标签: node.js async-await axios


    【解决方案1】:

    我认为您不应该在 .then 中返回异步响应,而是需要将 axios 响应作为承诺返回

    异步发送请求(){ 返回等待 axios(....) }

    在调用 sendRequest 函数时,您需要在前面提到 await 或简单地使用 .then 来捕获响应

    【讨论】:

    • 是的。就是这样。我花了一整天的时间......谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 2020-06-26
    • 2020-01-27
    • 2020-12-07
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多