node.js - 等待然后 .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);
});
}
解决方案
我认为您不应该在 .then 中返回异步响应,而是需要将 axios 响应作为承诺返回
异步 sendRequest() { 返回等待 axios(....) }
在调用 sendRequest 函数时,您需要在前面提及 await 或简单地使用 .then 来捕获响应
推荐阅读
- python - 用于连续视频的 Lstm
- bots - 如何让我的电报机器人用户与机器人分享他的联系人?
- websocket - 带有会话的 Vapor 3 Websocket
- assembly - 在汇编中打印浮点数
- scala - Java/Scala 中的随机 Avro 数据生成器
- excel - 仅在首次运行期间的 Excel VBA 错误代码
- sql - If else 使用大小写返回值
- python - pmdarima 的样本预测中的 ARIMA 是如何缩放的?
- python - Seaborn 的异常 - Pandas:AttributeError:'DatetimeIndex' 对象没有属性'mean'
- java - getStacktrace(),setStackTrace() 有什么用?我不明白这个函数有什么需要?