【发布时间】:2018-05-21 23:08:27
【问题描述】:
当我运行我的项目时,我得到了错误:
(node:5795) UnhandledPromiseRejectionWarning: Error: reply interface called twice
at Object.exports.assert (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hoek/lib/index.js:736:11)
at Function.internals.response (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hapi/lib/reply.js:164:10)
at bound (domain.js:301:14)
at Function.runBound (domain.js:314:12)
at reply (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hapi/lib/reply.js:72:22)
at bound (domain.js:301:14)
at runBound (domain.js:314:12)
at result.then (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hapi/lib/handler.js:105:36)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
(node:5795) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5795) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
null
我不知道这是错误还是我的代码错误?我是屏幕 hapi.js 问题,有人说错误是错误,另一个说'reply() times is limit in the same request'?如果是有限的,如何更改下面的代码?
```
export default async function (request, reply) {
if (request.auth.credentials.email !== request.payload.email) {
await User.findOne({ email: request.auth.credentials.email }).then(
(user) => {
if (user) {
User.findOne({ email: request.payload.email }).then(
(friend) => {
if (friend) {
const stringId = `${friend._id}`;
const friendExists = user.friends.filter(f => `${f}` === stringId).length > 0;
if (!friendExists) {
user.friends.push(friend);
user.save();
reply({ friend: { fullName: friend.fullName, _id: friend._id } });
} else {
reply(Boom.conflict('You have added already this friend'));
}
} else {
reply(Boom.notFound(`Friend ${request.payload.email} doesn't exist`));
}
},
);
} else {
reply(Boom.notFound('Cannot find user'));
}
},
);
} else {
reply(Boom.conflict('Cannot add yourself as a friend'));
}
}
Hapi@16.4.1
【问题讨论】:
-
与您的查询无关:您的代码需要一些清理,因为它不必要地复杂。示例:await promise.then 是模棱两可的。 const 变量 = await.promise 或 promise.then(variable=>{ ... })。为了展平嵌套的 if 并提高可读性,您可以使用带条件的 switch(true) 或仅使用查找错误并抛出的单数 if。此外,如果您从处理程序中抛出错误,则 hapi 将自动回复它,因此不要在整个过程中使用回复,而是尝试使用 throw Boom.notFound(...)。这是一个示例:jsfiddle.net/hoaobrook/qd43txzp
标签: javascript hapijs