How can I make this call to request in nodejs synchronous?

后端 未结 6 1719
旧时难觅i
旧时难觅i 2020-11-30 05:07

I have a function in my nodejs application called get_source_at. It takes a uri as an argument and its purpose is to return the source code from that uri. My problem is that

6条回答
  •  春和景丽
    2020-11-30 05:37

    I have to have a way to make sure I have the source code from a uri before continuing the control flow of my application - so if that's not by making the function synchronous, how can it be done?

    Given this entry point to your application:

    function app(body) {
        // Doing lots of rad stuff
    }
    

    You kick it off by fetching the body:

    request({ uri: uri }, function (error, response, body) {
        if(err) return console.error(err);
    
        // Start application
        app(body);
    }
    

    This is something you will have to get used to when programming for node.js (and javascript in general). There are control flow modules like async (which I, too, recommend) but you have to get used to continuation passing style, as it's called.

提交回复
热议问题