gpt4 book ai didi

node.js - 环回中的 'cb' 是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 23:10:31 25 4
gpt4 key购买 nike

我正在尝试学习环回,但我并不真正理解函数调用中的“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 和一个字符串?希望有人能帮忙。

最佳答案

所以你有一个异步函数 Person.greet 你会这样调用它:

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 只是一个参数。但通常使用“cb”、“done”或“next”作为标准做法。

关于node.js - 环回中的 'cb' 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31239954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com