首页 > 解决方案 > 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);
        });
}

标签: node.jspromise

解决方案


你不必通过响应,

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对象。


推荐阅读