0

Hello guys I'm trying to use the values received from the first api url request as params of the second api url. Therefore, I've created a for loop and with the idea that for every element in the array I'm iterating will send it as the parameter (these are as you can see below the variables user, language, city).

But I think it's not working because for loop is synchronous and the module request from nodejs is asynchronous. However I can't figure out another way to do it...

request(firstUrl, function(err, res, body) {

    let input = JSON.parse(body);

       for( var i=0 ;i< input.length; i++){

      var user= input[i]["user"]
            var language= input[i]["language"]
            var city= input[i]["city"]
      var query_url= encodeURIComponent('{"data":{"call":{"data":[{"text":'+city+',"language":'+language+',"user":'+user+',"id":'+id+'}]}}}')

              var secondUrl = {  

                url: `http://api.com/?request=${query_url}`,
                method: 'GET',
                headers: {
                  "Content-type": "application/json"

                }
              };                            
             request(secondUrl, function(err, res, body) {  
               let input = JSON.parse(body);
               console.log(err)
               console.log(res)
               console.log(input)

             }); 
          }

  return mongo.multiSave(input.contents)
                  
});
Defoe
  • 371
  • 1
  • 5
  • 17

2 Answers2

1

Indeed as the previous answer, promises can easily achieve this with much more readable code. checkout request-promise. I also use Promise.all to resolve all second requests promises in parallel. Here is my solution (I haven't tested the code)

request(firstUrl).then(function(body) {
  return JSON.parse(body);
}).then(function(input) {
  return Promise.all(secondRequests(input));
}).then(function(bodies) {
  bodies.forEach(function(body) {
    let input = JSON.parse(body);
    console.log(err)
    console.log(res)
    console.log(input)
  })
}).catch(function (err) {
});

function secondRequests(input) {
  var promises = [];
  for( var i=0 ;i< input.length; i++){
    var user= input[i]["user"]
    var language= input[i]["language"]
    var city= input[i]["city"]
    var query_url= encodeURIComponent('{"data":{"call":{"data":[{"text":'+city+',"language":'+language+',"user":'+user+',"id":'+id+'}]}}}')
    var secondUrl = {
      url: `http://api.com/?request=${query_url}`,
      method: 'GET',
      headers: {
        "Content-type": "application/json"
      }
    };
    promises.push(request(secondUrl));
  }
  return promises;
}
yunzen
  • 32,854
  • 11
  • 73
  • 106
mmohammad
  • 2,334
  • 2
  • 14
  • 23
0

Try using request-promise. Which will help you resolve

                var options = {
                method: 'POST',
                uri: 'http://api.posttestserver.com/post',
                body: {
                    some: 'payload'
                },
                json: true // Automatically stringifies the body to JSON
            };
            request(options).then(function (parsedBody) {

                let input = JSON.parse(parsedBody);

                for (var i = 0; i < input.length; i++) {

                    var user = input[i]["user"]
                    var language = input[i]["language"]
                    var city = input[i]["city"]
                    var query_url = encodeURIComponent('{"data":{"call":{"data":[{"text":' + city + ',"language":' + language + ',"user":' + user + ',"id":' + id + '}]}}}')

                    var secondOptions = {

                        url: `http://api.com/?request=${query_url}`,
                        method: 'GET',
                        headers: {
                            "Content-type": "application/json"

                        }
                    };

                    request(secondOptions).then(function (body) {
                        let input = JSON.parse(body);
                        console.log(err)
                        console.log(res)
                        console.log(input)

                    })

                }

                return mongo.multiSave(input.contents)


            }).catch(function (err) {

            });
Abhilash
  • 196
  • 11