首页 > 解决方案 > 等待然后 .then 没有得到 Axios Promise

问题描述

我正在通过我正在构建的应用程序跟踪我的方式。我已经编号了步骤来弄清楚什么被调用,什么不是。

我调用 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.jsasync-awaitaxios

解决方案


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

异步 sendRequest() { 返回等待 axios(....) }

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


推荐阅读