Node.js Asynchronous Function *Definition*

前端 未结 4 844
失恋的感觉
失恋的感觉 2020-12-30 15:16

Please, just to clear something up in my head...

I am used to writing using asynchronous functions in libraries, but how do I write my own?

To illustrate my

4条回答
  •  清酒与你
    2020-12-30 15:49

    This is not node.js module code, but I hope you get the idea.

    Functions are first class objects in JavaScript. That's why you can assign them to variables and pass them to other functions like any value. Once you have a reference to a function, you simply call it by putting () after the function reference.

    Example:

    function async_function_addthree(a, callback) {
        callback(a + 3);
    }
    

    This adds 3 to the first argument and then calls the second argument passing the result to it. Keep in mind that you can name the parameters however you want to. All that matters is that the second parameter will hold a function which you can call.

    But note: A function that accepts a callback is not automatically asynchronous. In this example, the code is still executed in the order it is defined, i.e. first async_function_addthree, then the callback and then everything that follows the call to async_function_addthree, e.g. the console.log.

    You could add a setTimeout and call the callback delayed:

    function async_function_addthree(a, callback) {
        setTimeout(function() {
            callback(a + 3);
        }, 1000);
    }
    

    This would call the callback after one second. Node.js even has a better way built-in, see jAndy's answer.

    But even if your code is not asynchronous, using callback can be a wise design choice since it allows you to easily change the behaviour of the function and make it asynchronous later on without breaking existing code.

提交回复
热议问题