node.js - promise.then 函数仅在内部定义时才有效
问题描述
从承诺中我无法真正理解一些东西。它曾经发生在我身上,也有回调。我不知道我没有看到什么。当我在“promise.then”中定义一个函数时,它可以正常工作。但是当我在外面用相同的参数定义相同的函数时,它说参数没有定义。这里发生了什么事?还有另一种方法可以让代码更清晰吗?
我发布了一个使用 express 和 axios npm 的代码,但我认为这不是问题。
app.get('/', function(req, res) {
//enviamos un mensaje a auth
axios
.post('http://localhost:8081', {
mensaje : 'Empiezo en api-rest.'
})
.then(function(response) {
//Ahora tengo que enviar la respuesta a priv
axios
.post('http://localhost:8082', response.data)
.then(function(responsePriv) {
console.log(responsePriv);
})
.catch(function(error) {
console.log(error);
});
})
.catch(function(error) {
console.log(error);
});
});
第二个代码
app.get('/', function(req, res) {
//enviamos un mensaje a auth
axios
.post('http://localhost:8081', {
mensaje : 'Empiezo en api-rest.'
})
.then(respuestaDeAuth(response))
.catch(function(error) {
console.log(error);
});
});
function respuestaDeAuth(response) {
//Ahora tengo que enviar la respuesta a priv
axios
.post('http://localhost:8082', response.data)
.then(function(responsePriv) {
console.log(responsePriv);
})
.catch(function(error) {
console.log(error);
});
}
解决方案
你不必通过响应,
app.get('/', function(req, res) {
//enviamos un mensaje a auth
axios
.post('http://localhost:8081', {
mensaje : 'Empiezo en api-rest.'
})
.then(respuestaDeAuth) // <-- Don't call your callback. Just pass it
.catch(function(error) {
console.log(error);
});
});
当您添加时then(respuestDeAuth(response))
,respuestDeAuth
函数立即执行,并带有未定义的变量调用响应。这就是为什么它的说响应没有定义。
您可以通过在外部词法环境中声明一个变量来做一个小实验来理解这一点,如const response = "Some data"
. 然后评论axios请求并尝试console.log()
. response
这次您不会看到错误,而是会看到response
变量的值
编辑
如果要添加res
参数,
app.get('/', function(req, res) {
//enviamos un mensaje a auth
axios
.post('http://localhost:8081', {
mensaje : 'Empiezo en api-rest.'
})
.then(() => respuestaDeAuth(res))
.catch(function(error) {
console.log(error);
});
});
您唯一需要注意的是,不要调用回调函数。在这里,我使用了一个函数,并在该函数内部调用respuestaDeAuth()
了原始res
对象。
推荐阅读
- c# - TcpListener 没有被执行
- sql - 每个子条款上带有参数的联合 SQL 视图
- json - 如何在 AWS CLI 上使用 AWS-RunRemoteScript?
- azure - Chrome 已开始阻止 azure blob 存储下载
- java - 如何在 android studio 中创建计时器?
- c# - 统一调用包括在另一个协程中播放动画的协程使动画仅播放 0.1 秒
- c++ - 将预处理器指令作为语句的一部分
- javascript - 如何将数组写入电子表格。setValues 抛出“无法将数组转换为对象”
- tensorflow - 如何在 TFX 管道中包含超参数调整?
- c# - 将 Java 库公开给 .NetCore2.2