使用afterRemote钩子在远程方法的环回中发送响应

我正在尝试处理需要发送邮件的请求。 为了响应请求而不等待邮件发送,我正在发送一个afterRemote钩子邮件。 该方法似乎运行正常,并发送邮件,但由于某种原因,cb函数不执行,因此在客户端请求保持未答复。 问题是在console.log("Here");cb(null,{});的代码,你可以看到我有console.log("Here");cb(null,{}); 那里和第一个命令得到执行,但不是看起来第二个。

  user.joinEntity = function(data, cb) { var loopbackCtx = user.app.loopback.getCurrentContext(); var userId=loopbackCtx.accessToken.userId; if(false){ cb( new Error("Cant join that Entity."),{}); }else{ user.find({where:{id:userId}},function(err,applicant_instance){ if (err) cb(err,{}); if(applicant_instance.length>0) user.find({where:{id:data.ownerId}},function(err,founder_instance){ if (err) cb(err,{}); if(founder_instance.length>0) user.app.models.EntityApplication.create({email:applicant_instance[0].email,userId:userId,EntityFounder:founder_instance[0].id,Entity:data.id,Status:"pending"},function(err,Entity_Application_Instance){ if (err) cb(err,{}); loopbackCtx.join_entity={applicant:applicant_instance[0].email,entity:data.name,to:founder_instance[0].email}; console.log("Here"); cb(null,{}); }); }); }) } } user.afterRemote('joinEntity',function(){ var loopbackCtx = user.app.loopback.getCurrentContext(); user.app.models.Email.send({ to: loopbackCtx.join_entity.to, from: 'mailer@domain.org', subject: 'Application to enter your Entity', // text: '<strong>HTML</strong> tags are not converted' html: 'User <strong>'+loopbackCtx.join_entity.applicant+'</strong> wants to enter Entity by the name of <strong>'+loopbackCtx.join_entity.entity+'</strong>' }, function(err) { if (err) throw err; console.log('> email sent successfully'); }); }); 

通常情况下,您需要确保在远程挂接上执行next()callback,以告诉LB(或者说Express)您希望这个特定的中间件允许处理继续。 如果你不打电话next()那么你基本上就是告诉Express,这是中间件处理的结束。 确保接受远程钩子的所有三个参数,然后在方法操作完成时执行next()

 user.afterRemote('joinEntity',function(ctx, instance, next){ // *** notice arguments above! var loopbackCtx = user.app.loopback.getCurrentContext(); user.app.models.Email.send({ to: loopbackCtx.join_entity.to, from: 'mailer@domain.org', subject: 'Application to enter your Entity', // text: '<strong>HTML</strong> tags are not converted' html: 'User <strong>'+loopbackCtx.join_entity.applicant+'</strong> wants to enter Entity by the name of <strong>'+loopbackCtx.join_entity.entity+'</strong>' }, function(err) { // *** notice the correct way to indicate an error! if (err) { next(err); } console.log('> email sent successfully'); // *** Now tell Express to keep processing middleware next(); }); });