What is cb() in Node?

前端 未结 3 1354
离开以前
离开以前 2021-02-01 18:29

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

For example:

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

相关标签:
3条回答
  • 2021-02-01 18:31

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

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

    0 讨论(0)
  • 2021-02-01 18:36

    cb in 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 bananas if you so desire - it's just an argument).

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

    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 object from 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 widely in 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.

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

    0 讨论(0)
  • 2021-02-01 18:36

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

    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.

    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);
        }
    });
    
    0 讨论(0)
提交回复
热议问题