What is cb() in Node?

前端 未结 3 1360
离开以前
离开以前 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: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.

提交回复
热议问题