Node.js Asynchronous Function *Definition*

前端 未结 4 809
失恋的感觉
失恋的感觉 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条回答
  •  -上瘾入骨i
    2020-12-30 15:57

    I came across this question while looking for the answer to it myself.

    Basically, to write an asynchronous function in node, one of the arguments you give it should be a function; that function you'll call later on in your async function.

    Then, when people are calling your function, they'll be able to define that function.

    Here's an example of my code that I wrote in a synchronous way which didn't work, and how I rewrote it to be asynchronous and actually work.


    The following code DOES NOT WORK:

    //synchronous function that doesn't work
    var google_request  = function(animal_name, sessionid){
        var options = {
            url: 'http://google.com',
            method: 'POST',
            json: {
                "animal": animal_name,
                "sessionid": sessionid
            }
        };
    
        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                return body;
            }
        });
    };
    
    //use your function
    var body = google_request("ant", "session1")
    console.log(body); //this will return undefined
    

    The following code DOES work:

    //asynchronous function
    var google_request  = function(animal_name, sessionid, callback_function){
        var options = {
            url: 'http://google.com',
            method: 'POST',
            json: {
                "animal": animal_name,
                "sessionid": sessionid
            }
        };
    
        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                callback_function(body);
            }
        });
    };
    
    //use your function
    google_request("ant", "session1", function(body){
        console.log(body); 
    )};
    

    This is maybe not the simplest example, but the changes I made to this function were very simple; I passed my function a third argument, called "callback_function", and instead of returning "body", I called my callback_function on body. Then below I used my function in the usual "Node" manner, instead of the synchronous manner.

    You might also find this thread informative: How do I return the response from an asynchronous call?

提交回复
热议问题