【问题标题】:Writing app logic in custom model strongloop在自定义模型 strongloop 中编写应用程序逻辑
【发布时间】:2016-01-05 23:48:48
【问题描述】:

您好,我是 strongloop 的新手,我想知道我可以在自定义模型中编写我的应用程序逻辑吗?就像下面的例子一样,我从订单表中获取数据,成功后我想在我的逻辑中使用它的响应。

Orders.createOrder = function(cb) {
Orders.findById( userId, function (err, instance) {
    response = "Name of coffee shop is " + instance.name;
    cb(null, response);

/***** want to write my logic here *****/


    console.log(response);
});
cb(null, response);
};
Orders.remoteMethod(
'createOrder',
{
  http: {path: '/createOrder', verb: 'get'},
  returns: {arg: 'status', type: 'string'}
}
);  

那么它是写的地方还是我必须在其他地方写呢?

【问题讨论】:

    标签: strongloop


    【解决方案1】:

    您的代码有几个问题,但答案是肯定的。

    您应该在应用程序逻辑完成时调用回调函数cb,而不是之前。此外,您应该注意将任何错误反馈到cb,否则您将面临一些大的调试难题。

    此外,您需要特别注意调用回调的方式。在您当前的代码中,cb 将在createOrder 的最后和findById 的任何请求中被调用两次。这不好,因为对于一个请求,您告诉服务器您已经完成了两个。此外,在findById 完成之前,立即调用createOrder 末尾的回调。

    所以修正后的代码看起来像这样

    Orders.createOrder = function(cb) {
      Orders.findById( userId, function (err, instance) {
        // Don't forget stop execution and feed errors to callback if needed
        // (other option : if errors are part of normal flow, process them and continue of course)
        if (err) return cb(err);
        
        response = "Name of coffee shop is " + instance.name;
        console.log(response);
        
        // Application logic goes there
        
        // Complete the remote method
        cb(null, response);
      });
      // No calls here to the callback
    };
    Orders.remoteMethod(
    'createOrder',
    {
      http: {path: '/createOrder', verb: 'get'},
      returns: {arg: 'status', type: 'string'}
    }
    );  

    【讨论】:

    • 谢谢您的回复... :)
    • 如果我的代码有帮助,请接受我的回答或单击向上箭头表示它是相关的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多