我有以下代码:
"use strict";
const Raven = require("raven");
Raven.config(
"test"
).install();
module.exports = function(Reservation) {
function dateValidator(err) {
if (this.startDate >= this.endDate) {
err();
}
}
function sendEmail(campground) {
return new Promise((resolve, reject) => {
Reservation.app.models.Email.send(formEmailObject(campground),
function(
err,
mail
) {
if (err) {
console.log(err);
Raven.captureException(err);
reject(err);
} else {
console.log(mail);
console.log("email sent!");
resolve(mail);
}
});
});
}
function formEmailObject(campground) {
return {
to: "loopbackintern@yopmail.com",
from: "noreply@optis.be",
subject: "Thank you for your reservation at " + campground.name,
html:
"<p>We confirm your reservation for <strong>" +
campground.name +
"</strong></p>"
};
}
Reservation.validate("startDate", dateValidator, {
message: "endDate should be after startDate"
});
Reservation.observe("after save", async function(ctx, next) {
try {
const campground = await Reservation.app.models.Campground.findById(
ctx.instance.campgroundId
);
const mail = await sendEmail(campground);
next();
} catch (e) {
Raven.captureException(e);
next(e);
}
});
};
抱歉,格式不正确。当流程完成后,我收到此错误:
( Node :3907)UnhandledPromiseRejectionWarning:未处理的 promise 拒绝(拒绝 ID:1):错误:回调已被调用。
我在两个地方调用 next() 回调,一处在 try 代码中,一处在 catch 代码中。我假设当一切顺利时,下一个回调仅被调用一次,当出现问题时也是如此。但好像被调用了两次,不知道为什么。
我还尝试在 try/catch 代码之外调用 next,但它会导致相同的错误。如果我只留下捕获代码中调用的下一个,则不会引发错误。
有什么想法吗?谢谢!
最佳答案
如果您使用异步函数,则不应显式调用 next,它会自动调用。
check out this github issue for loopback async/await
所以你的钩子(Hook)可以像下面这样。
Reservation.observe("after save", async ctx => {
try {
const campground = await Reservation.app.models.Campground.findById(
ctx.instance.campgroundId
);
const mail = await sendEmail(campground);
} catch (e) {
Raven.captureException(e);
throw e;
}
});
注意:除非您想修改/处理错误,否则不需要将其包装在 try catch 中。
关于node.js - 错误: Callback was already called in loopback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50561739/