[英]Why is Axios not returning a promise?
我有以下代码,但没有控制台输出。 似乎无论我做什么,它都不会进入then()
或catch()
。
axios
.post(url, {test: "0"})
.then(console.log)
.catch(console.error);
有趣的是,请求被发布并在另一端接收。 我还可以通过与邮递员模拟来验证端点是否正确响应。 这哪里会失败?
编辑:它变得更奇怪了:我尝试了以下操作,它立即打印了承诺:
console.log(await axios.post(url, {test: "0"}));
不幸的是,我被迫使用 Node v8.11.1 - 这可能是问题吗?
编辑 2 : .then(console.log)
只是另一种写法.then(response => console.log(response))
但只是为了确保我去了官方文档并使用了推荐的方式:
axios
.post(url, {test: "0"})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
问题仍然存在。
根本不是 Axios 的问题。 Azure 在 POST 后立即终止了我的进程,并没有等待 Promise 解决。 如果有人遇到类似问题,请参阅Promise is not working in azure function app javascript
将 console.log 函数作为解析回调传递时,您将丢失日志函数的上下文。 上下文是控制台
您将上下文重新绑定到函数日志
axios
.post(url, {test: "0"})
.then(console.log.bind(console))
.catch(console.error.bind(console));
axios 承诺工作。 函数日志上下文绑定: https : //jsfiddle.net/dwk1nrpe/8/
使用箭头函数不会丢失上下文
axios
.post(url, {test: "0"})
.then((res) => console.log(res))
.catch((err) => console.error(err));
希望它能解决你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.