如何修复回调已经在环回模型中调用

How to fix the callback was already called in loopback model

我尝试在环回模型中扩展 api。 在模型中,我使用了 findOne、create 等模型的标准 api。 示例代码如下

Subscriber.findOne({
 where : {
      email : "............."
 },
 function(err, instance){
      if(instance)
      {
           cb(null,instance);
           response = "success";
      }
 }
 cb(null, response);

但是当我调用这个扩展的时候api,就出现了错误

throw err:// Rethron non-MsSQL errors
    ^

Error: Callback was already called.

如何解决这个错误?

您需要在 if 回调中使用 return,因为您还没有使用 else 语句。将您的代码更改为:

Subscriber.findOne({
  where: {
    email: "............."
  },
  function(err, instance) {
    if (instance) {
      response = "success";
      return cb(null, instance);
    }
  },
  return cb(null, response);
});

更好的代码:

Subscriber.findOne({
  where: {
    email: "............."
  },
  (err, instance) => {
    if (err) return cb(err)
    
    if (!instance) {
      let error = new Error()
      error.status = 404
      error.message = 'Subscriber not found.'

      return cb(error)
    }
      
    cb(null, instance)
  }
})