node.js Node 中的 cb() 是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31780872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:12:33  来源:igfitidea点击:

What is cb() in Node?

node.js

提问by PositiveGuy

Where are people getting cb() from, is this a Node thing or vanilla JS thing?

人们从哪里获得 cb(),这是一个 Node 的东西还是 vanilla JS 的东西?

For example:

例如:

Managing Node.js Callback Hell with Promises, Generators and Other Approaches

使用 Promise、生成器和其他方法管理 Node.js 回调地狱

they're using cb() to I guess callback and return an error or a value or both in some cases depending on what the callback function sig is?

他们使用 cb() 来猜测回调并在某些情况下返回错误或值或两者都取决于回调函数 sig 是什么?

回答by Joshua

cbin the context you're describing it is how a vanilla callback function is passed into a (typically) asynchronous function, which is a common pattern in node.js (it's sometimes labelled next, but you can call it bananasif you so desire - it's just an argument).

cb在您描述的上下文中,它是如何将普通回调函数传递到(通常)异步函数中,这是 node.js 中的常见模式(有时标记为 next,但bananas如果您愿意,可以调用它- 它是只是一个论点)。

Typically the first argument is an errorobject (often false - if all went as planned) and subsequent arguments are data of some form.

通常,第一个参数是一个error对象(通常为 false - 如果一切按计划进行),随后的参数是某种形式的数据。

For example:

例如:

function myAsyncFunction(arg1, arg2, cb) {
    // async things
    cb(false, { data: 123 });
}

then using this function:

然后使用这个函数:

myAsyncFunction(10, 99, function onComplete(error, data) {
    if (!error) {
        // hooray, everything went as planned
    } else {
        // disaster - retry / respond with an error etc
    }
});

Promises are an alternative to this design pattern where you would return a Promise objectfrom myAsyncFunction

Promises 是这种设计模式的替代方案,您可以从中返回一个Promise 对象myAsyncFunction

For example:

例如:

function myAsyncFunction2(arg1, arg2) {
    return new Promise(function resolution(resolve, reject, {
        // async things
        resolve({ data: 123 });
    });
}

then using this function:

然后使用这个函数:

myAsyncFunction2(10, 99)
    .then(function onSuccess(data) {
        // success - send a 200 code etc
    })
    .catch(function onError(error) {
        // oh noes - 500
    });

They're basically the same thing, just written slightly differently. Promises aren't supported especially widelyin a native form, but if put through a transpiler (I'd recommend babel) during a build step they should perform reliably enough in a browser too.

它们基本上是一样的,只是写法略有不同。承诺没有特别的广泛支持原生形式,但如果通过transpiler把(我建议通天期间生成步骤,他们应该在浏览器足够可靠执行过)。

Callbacks will always work in a browser with no shimming / transpilation.

回调将始终在浏览器中工作,没有填充/转换。

回答by jfriend00

node.js has lots of asynchronous operations that take a completion callback as an argument. This is very common in various node.js APIs.

node.js 有许多异步操作,它们将完成回调作为参数。这在各种 node.js API 中很常见。

The node.js convention for this callback is that the first argument passed to the callback is an error code. A falsey value for this first argument means that there is no error.

此回调的 node.js 约定是传递给回调的第一个参数是错误代码。第一个参数的 falsey 值意味着没有错误。

For example:

例如:

fs.readFile("test.txt", function(err, data) {
    if (!err) {
        console.log("file data is: " + data);
    }
});

A function you create yourself may also define it's own callback in order to communicate the end of one or more asynchronous operations.

您自己创建的函数也可以定义它自己的回调,以便传达一个或多个异步操作的结束。

function getData(id, cb) {
    var fname = "datafile-" + id + ".txt";
    fs.readFile(fname, function(err, data) {
        if (err) {
            cb(err);
        } else if (data.slice(0, 6) !== "Header"){
            // proper header not found at beginning of file data
            cb(new Error("Invalid header"));
        } else {
            cb(0, data);
        }
    });
}

// usage:
getData(29, function(err, data) {
    if (!err) {
        console.log(data);
    }
});

回答by davesnx

From the Vanilla JS, you can declare a function and pass throuw parameters a declaration of another function, that can called async

从 Vanilla JS,您可以声明一个函数并通过参数传递另一个函数的声明,该函数可以调用 async

https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks

https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks