【问题标题】:Promise not returning any data for fetch return承诺不返回任何数据以获取返回
【发布时间】:2018-08-04 04:53:49
【问题描述】:

我正在构建一个使用 mongoose 访问数据库的快速路由器。我目前的问题依赖于这段代码:

app.use("/authreset", (req, res) => {
    authenticator
        .resetPassword(
            req.body.username,
            req.body.password,
            req.body.token,
            req.body.type
        )
        .then((response, error) => {
            if (error) throw new Error(error);

            console.log('*****************');
            console.log(response);

            if (!response) {
                res.sendStatus(401);
                return;
            }
        })
        .catch(error => {
            console.log('*****************');
            console.log(error);
            if (error) throw new Error(error);
        });

});

resetPassword 使用以下 mongoose 调用:

return UserModel
    .findByIdAndUpdate(user.id, data, { new: true })
    .exec();

由于某种原因,我的路由被调用并且响应很好(检查了console.log(response) inside promise)。

我的问题是响应永远不会发送回客户端,导致 fetch 调用超时。

为什么我的 promise 没有返回数据?

【问题讨论】:

  • 哪个promise是用来返回数据的,它是用来把数据返回到哪里的? - 在您发布的代码中看不到任何返回数据,甚至在响应中发送数据

标签: javascript express mongoose promise express-router


【解决方案1】:

呃,你记录了response,但你从来没有send它(或者至少回复一个状态码)?

您的代码应该看起来更像

app.use("/authreset", (req, res) => {
    authenticator.resetPassword(
        req.body.username,
        req.body.password,
        req.body.token,
        req.body.type
    ).then(response => {
        console.log(response);

        if (!response) {
            return res.sendStatus(401);
        } else {
            return res.sendStatus(200); // <<<
        }
    }, error => {
        console.log(error);
        return res.sendStatus(500);
    });
});

请注意,then 回调永远不会使用多个参数调用,因此您正在检查的 error 不会发生。在catch 处理程序中,如果没有进一步处理,您永远不应该重新throw 错误。我也是changed .then(…).catch(…) to the more fitting .then(…, …)

【讨论】:

  • 其实我不需要客户端的响应,只需要状态。 401失败,200成功。我删除了res.send(response),但我的客户仍然卡住了......
  • 没什么,但我遇到了问题。我需要return res.sendStatus(200) 或其他什么。我将编辑您的代码。感谢您的帮助。
  • 也许有一点解释与代码一起去?
  • @jfriend00 啊,OP的编辑删除了我解释的主要部分,没有注意到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 2018-08-25
  • 2018-05-16
  • 1970-01-01
  • 2020-04-06
  • 2016-06-15
  • 2019-05-20
相关资源
最近更新 更多