HapiJS回复被调用两次

时间:2017-02-02 03:19:27

标签: api unit-testing hapijs

我收到此错误消息时使用下面的代码段

Unhandled rejection Error: reply interface called twice

请注意,我正在将return用于所有的回复()界面

Locations
    .findOne({
      _id: request.params.id,
      activationCode: payload.activationCode
    }).then((location) => {
      if (!location) {
        return reply(Boom.notFound('Location not found'))
      }
      locationObject = location
      if (payload.password !== payload.confirmPassword) {
        return reply(Boom.badRequest('Password and Confirm Password must match'))
      }
      if (!payload.terms) {
        return reply(Boom.badRequest('Must agree to Terms & Conditions'))
      }
      return newPaymentMethod.save()
    }).then((paymentMethod) => {
        .....
        return user.save() // user is defined at .....
    }).then(() => {
      return reply({ token: helpers.createJwt(userObject) })
    }).catch((err) => {
      return reply(Boom.wrap(err))
    })

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

由于未正确使用承诺,您似乎陷入了困境。我猜你正在一个你可以访问reply的路由处理程序中执行你的代码片段。

当您在承诺链中return回复时,您return.then的价值转移到下一个reply(承诺)并同时调用reject来自外部范围。

我建议您使用承诺reply(Boom.method())来处理错误,这样您只需要承诺.catch()中的ELSE个。{/ p>

答案 1 :(得分:1)

因为你最终链接了承诺

.then(() => {
  return reply({ token: helpers.createJwt(userObject) })
}).catch((err) => {
  return reply(Boom.wrap(err))
})

如果任何reply条件为真,您可以拨打if两次。 简单的解决方案是在if条件中抛出错误为真 - 因为catch块中已经存在Boom.wrap

相关问题