0

I've just started with Node.js and callbacks are something I'm getting used to it. Sometimes it just gives me a bad time. I have a function dwnloadData() which downloads the data and append the data into an empty array and send that array.

Here for downloading I'm using callback and I'm getting arrData empty Can someone pls let me know the correction.

Requirement: arrData, the array should have all the data downloaded using for loop and should return using promise.

downloadData(url) {

        return new Promise((resolve, reject) => {
            var arrData = [];

            for (var i = 0; i < url.length; i++) {
                request.get(url[i], function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        var content = body
                        var jsonArray = JSON.parse(content);
                    }
                });
               arrData.push(jsonArray)
            }
        resolve(arrData)
        });
    }
1
  • Your request.get callback happens later. arrData.push happens immediately. Commented Jun 14, 2019 at 12:13

3 Answers 3

1

You are looping through the url and getting the jsonData which is only valid inside the callback function. Because you don't know when the request.get will resolve.

So what are you basically doing is, Looping over the urls, initiating the GET request. But not waiting for the result and returning the function. (also again, you need to .push inside the callback.

What you can do is, making a array of promises and run it via Promise.all which automatically returns an array. And bonus, you are running the GET requests in parallel.

function downloadData(url) {
    const promises = [];
    for (let i = 0; i < url.length; i++) {
        promises.push(
            new Promise((resolve, reject) => {
                request.get(url[i], function (error, response, body) {
                    if (!error && response.statusCode == 200) {
                        const content = body
                        const jsonArray = JSON.parse(content);
                        resolve(jsonArray)
                    }else{
                        resolve()
                    }
                });
            })
        );
    }
    return Promise.all(promises);
}

But use a promise based HTTP library like axios to do promise chaining or async-await naturally.

Sign up to request clarification or add additional context in comments.

Comments

0

Use async/await with request-promise module.For example

const request = require('request-promise');

app.get('/', async (req, res, next) => { 

 // ...
 const result = await downloadData(url); 

});

async function downloadData(url) {

  const arrData = [];

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

    try {

      let data = await request.get(url[i]);

      if (data) {
        arrData.push(JSON.parse(data))
      }

    }
    catch (err) {
      console.log(err)
    }

  }

 return arrData;

}

Comments

0

This is because you used call back function inside a promise, When you call an api it doesn't wait there because of asynchronous, it go further and called resolve.

var rp = require('request-promise');
downloadData(url) {

    return new Promise(async (resolve, reject) => {
        var arrData = [];
        let jsonArray;

        for (var i = 0; i < url.length; i++) {
            try{
                let res = await rp.get(url[i]);
                if (res.statusCode === 200) {
                    let content = body
                    jsonArray = JSON.parse(content);
                }
            }catch (e) {
                reject(e)
            }
            arrData.push(jsonArray)
        }
        resolve(arrData)
    });
}

3 Comments

use request-promise here
I'm already using normal promise, it won't affect if i use request-promise right ?
returning empty data

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.