什么' cb'在环回中意味着什么?

时间:2015-07-06 07:25:08

标签: node.js callback loopbackjs

我正在尝试学习环回,但我并不真正理解' cb'在函数调用中表示。我读了这个In loopback documentation what does variable 'cb' stands for?,我对nodejs中的回调有基本的了解,但我不理解环回中的cb。 例如,http://docs.strongloop.com/display/public/LB/Remote+methods

module.exports = function(Person){

    Person.greet = function(msg, cb) {
      cb(null, 'Greetings... ' + msg);
    }

    Person.remoteMethod(
        'greet',  
        {
          accepts: {arg: 'msg', type: 'string'},
          returns: {arg: 'greeting', type: 'string'}
        }
    ); 
};

这个cb是什么意思?我们怎么知道它接受两个参数,null和一个字符串?希望有人可以提供帮助。

3 个答案:

答案 0 :(得分:11)

所以你有一个异步函数Person.greet('hello', function(err){ ... }); ,你可以像这样调用它:

'hello'

请注意,在function callback(err){ ... } Person.greet('hello', callback); 传递了第二个参数后,它实际上是一个函数。它也可以在外面用名称定义并以这种方式传递:

Person.greet

现在它看起来确切地定义了Person.greet = function(msg, cb) { cb(null, 'Greetings... ' + msg); }

cb

这里的区别只是在定义中它使用了不同的名称:cb。它可以使用任何名称,因为它git checkout -b old-state 0d1d7fc32 只是一个参数。但通常使用“cb”,“done”或“next”作为标准做法。

答案 1 :(得分:3)

看看答案,在我看来,这两个问题中只有一个得到了回答。

问题1:cb是什么意思?

之前已经回答过它是回调函数的缩写。

问题2:我们怎么知道它接受两个参数,null和一个字符串?

您可以在远程方法的return选项中定义此选项,该选项根据docs执行以下操作:

  

描述远程方法的回调参数;请参阅参数说明。假设错误的论点;不要指定。

所以,如果我们看一下你的例子

Person.remoteMethod(
    'greet',  
    {
      accepts: {arg: 'msg', type: 'string'},
      returns: {arg: 'greeting', type: 'string'}
    }
); 

您在此处定义了回调参数

callback(err, greeting: string)

让我们从文档中得到另一个例子:

    MyModel.remoteMethod('download', {
        isStatic: true,
        returns: [
            { arg: 'body', type: 'file', root: true },
            { arg: 'Content-Type', type: 'string', http: { target: 'header' } },
        ],
    });

对于此示例,回调将为

callback(err, body: file, Content-Type: string)

,用法就是这样

cb(null, stream, 'application/octet-stream');

答案 2 :(得分:1)

我刚刚遇到同样的问题,经过几个小时的挫折后,我找到了官方的答案。

https://docs.strongloop.com/display/public/LB/Remote+methods#Remotemethods-Howtodefinearemotemethod

选项接受:

  

定义远程方法接受的参数。这些参数映射   到您定义的静态方法。对于上面的例子,你可以看到   函数签名:Person.greet(姓名,年龄,回调)...... name是   第一个参数,age是第二个参数,回调是   由LoopBack自动提供(不要在你的指定中指定它)   accepts数组)。有关详细信息,请参阅参数说明。默认如果   未提供的是空数组,[]。