【问题标题】:How to fix the callback was already called in loopback model如何修复回调已在环回模型中调用
【发布时间】:2019-04-24 22:38:09
【问题描述】:

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

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.

如何解决这个错误?

【问题讨论】:

    标签: mysql node.js rest loopbackjs


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      更好的代码:

      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)
        }
      })

      【讨论】:

        猜你喜欢
        • 2018-11-06
        • 1970-01-01
        • 1970-01-01
        • 2019-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        相关资源
        最近更新 更多