Search code examples
node.jsnpmnpm-request

Request npm module - Request inside of request


I am using request npm module and making 4 request inside of mainstream request. To say the conclusion first, only two of four request are succeed randomly.

Here is my code below.

router.get('/', function(req, res){
    //TODO
    request(url, function(error, response, body) {
        if(err) throw error;
        //TODO-
        request(comnURL, function(errp,resp, body){
            if(errp) throw errp;
            comnBODY = body;
            console.log(body);
            console.log("\n\n");
        });
        request(intrURL, function(errp,resp, body){
            if(errp) throw errp;
            intrBODY = body;
            console.log(body);
            console.log("\n\n");
        });
        request(reptURL, function(errp,resp, body){
            if(errp) throw errp;
            reptBODY = body;
            console.log(body);
            console.log("\n\n");
        });
        request(addiURL, function(errp,resp, body){
            if(errp) throw errp;
            addiBODY = body;
            console.log(body);
            console.log("\n\n");
        });
        //TODO-
    });
});

Every request of response is different randomly, chosen 2 of 4 sub-request. What could be the reason of this and how to avoid it.


Solution

  • You code has some syntax errors, but works fine. This can be an asynchronous problem. If you want this 4 request executing in order, you must put in this way:

    'use strict';
    
    const request = require('request')
    
    request('https://jsonplaceholder.typicode.com/posts/5', function(error, response, body) {
        if(error) throw error;
        //TODO-
        request('https://jsonplaceholder.typicode.com/posts/1', function(errp,resp, body){
            if(errp) throw errp;
            let comnBODY = body;
            console.log(body);
            console.log("1\n\n");
            request('https://jsonplaceholder.typicode.com/posts/2', function(errp,resp, body){
                if(errp) throw errp;
                let intrBODY = body;
                console.log(body);
                console.log("2\n\n");
                request('https://jsonplaceholder.typicode.com/posts/3', function(errp,resp, body){
                    if(errp) throw errp;
                    let reptBODY = body;        
                    console.log(body);
                    console.log("3\n\n");
                    request('https://jsonplaceholder.typicode.com/posts/4', function(errp,resp, body){
                        if(errp) throw errp;
                        let addiBODY = body;
                        console.log(body);
                        console.log("4\n\n");
                    });
                });
            });
        });
    });
    

    Another approach is using a promise way, for that you can use request-promise module.