0

I want to use NodeJS to get the response from 2 urls, and put them in an array for later processing.

I am unable to store the body/resp outside the request.get function. Resp has undefined outside request.get.

Any suggestion what I am doing wrong? Thx

var msurls = ["http://example.org/get1", "http://example.org/get2"];
var request = require("request");
var msresult = [];

msurls.forEach(function(msurl) {
        var resp;
        request.get(msurl,function(error,response,body){
                if(error) {
                        console.log(error);
                } else {
                        resp = body;
                }
        });
        msresult.push(resp);
});
console.log(msresult);
2

3 Answers 3

0

You have an issue with the timing of your code. Your msresult.push(resp); is fired before you request.get has finished, so you are pushing resp that doesn't have a value yet.

I think you can use await as so... (I may be wrong though)

var msurls = ["http://example.org/get1", "http://example.org/get2"];
var request = require("request");
var msresult = [];

msurls.forEach(function(msurl) {
    await request.get(msurl, function(error, response, body){
        if(error) {
            console.log(error);
        } else {
            msresult.push(body);
        }
    });
});
console.log(msresult);
1
  • You're using await with a callback which is wrong, if you use a callback, request is not going to return a Promise
    – calbertts
    May 22, 2018 at 13:26
0

Take a look at Promise.all() - it allows you to execute multiple async requests.

Cleaner solution would be:

const request = require("request");

const getData = async (requests) => {
  return Promise.all(requests);
};

const doWork = async () => {
  const msurls = ["http://example.org/get1", "http://example.org/get2"];
  const requests = msurls.map(url => request.get(url));

  const result = await getData(requests);
  console.log(result);
  return result;
};

As for further learning, take a look into ES6 features Node supports and read up about asynchronous programming in Javascript.

0

request module doesn't support promises, use request-promise-native instead, if not, you have to use callbacks as @Gediminas wrote.

I do prefer this even cleaner solution which is more modern javascript:

let msurls = ["http://example.org", "http://example.org"]
let request = require("request-promise-native")

async function doRequests() {
    return await(Promise.all(
        msurls.map(async msurl => await request(msurl)))
    )
}

doRequests().then(msresult => console.log(msresult))

You already have an array with the results and the code looks synchronous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.