【问题标题】:Pass simple function directly to es6 promise.then [duplicate]将简单函数直接传递给es6 promise.then [重复]
【发布时间】:2015-11-09 04:38:53
【问题描述】:

我在快速路由函数中有以下 ES6 承诺链(即 res 是快速响应对象)。 findQnameForId 是一个 Promise,mongoDelete 和 mysqlDelete 都返回 Promise。当我使用注释掉的代码而不是当前的最后一行时,链可以工作,但我的问题是为什么我不能将 res.send 直接传递给then(如图所示)并让它将结果返回给客户端?

findQnameForId
.then(mongoDelete)
.then(mysqlDelete)
.then(res.send, res.status(400).send);
// .then(function(result) {
//  res.send(result);
// })
// .catch(function(err) {
//  res.status(400).send(err);
// });

【问题讨论】:

  • 使用箭头函数:.then(() => res.send(), err => res.status(400).send(err)) 这就是它们的用途。

标签: javascript callback es6-promise


【解决方案1】:

我认为这与回调期间没有正确的 this 值有关。它可能适用于bind

var fourhundred = res.status(400);
findQnameForId
.then(mongoDelete)
.then(mysqlDelete)
.then(res.send.bind(res), fourhundred.send.bind(fourhundred));

...但请继续阅读。

如果你确定res.status(400) 返回res,那就简单一点:

findQnameForId
.then(mongoDelete)
.then(mysqlDelete)
.then(res.send.bind(res), res.status(400).send.bind(res));

...但请继续阅读。

请注意,在任何一种情况下,即使成功(在调用 then 之前),您也会调用 res.status(400),这可能不是您想要的。所以你可能需要一个中间立场:

findQnameForId
.then(mongoDelete)
.then(mysqlDelete)
.then(res.send.bind(res), function(err) {
    res.status(400).send(err));
});

这样,您只有在发生错误时才调用res.success(400)

【讨论】:

  • 谢谢,虽然我最终需要使用.then(res.status(200).send.bind(res),... - 不知道为什么在这种情况下没有使用默认的 200。 this的奇迹!
  • @SimonH:很高兴为您提供帮助。但如果你有.then(res.status(200).send.bind(res), res.status(400).send.bind(res)),请注意你调用的是res.status(200),然后是.bind(res),然后是res.status(400),然后是.bind(res),然后是.then。这意味着对status 的最后一次调用将使用值 400。但是如果你正在做我在答案末尾所做的事情,那么status(400) 只会在错误情况下发生并且你很好形状。 :-)
  • 不确定是运气还是判断,但我使用了您的最终 sn-p 和 status(200) 添加。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2016-02-07
  • 2018-01-15
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2016-01-21
  • 2012-01-14
相关资源
最近更新 更多