wait until http gets request before moving to next loop iteration

Viewed 53

I am getting some youtube video ids and storing them in an array then I looped on each video id to determine the size of that id's thumbnail. What I am trying to achieve now is, i want my loop to wait until my http is done before going to the next loop iteration. How can I achieve this? Thanks in advance.

const url = require('url')
const http = require('http')
const sizeOf = require('image-size')

//example array
const myArr = ['ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw', 'ficzsusamA0Mw']

for (var i = 0; i < myArr.length; i++) {
  const imgUrl = `http://img.youtube.com/vi/${myArr[i}/maxresdefault.jpg`
  const options = url.parse(imgUrl)

  http.get(options, function(response) {
    const chunks = []
    response.on('data', function(chunk) {
      chunks.push(chunk)
    }).on('end', function() {
      const buffer = Buffer.concat(chunks)
      console.log(`${i}, ${JSON.stringify(sizeOf(buffer))}`)
    })
  })
}

1 Answers

If I were in your shoes I would use Async/Await the code would be something like this :


const url = require("url");
const http = require("http");
const sizeOf = require("image-size");

const callHttp = async (youtubeId, options) => {
  return new Promise((resolve) => {
    http.get(options, function (response) {
      let chunks = [];
      response
        .on("data", function (chunk) {
          chunks.push(chunk);
        })
        .on("end", function () {
          const buffer = Buffer.concat(chunks);
          console.log(`${i}, ${JSON.stringify(sizeOf(buffer))}`);
          console.log("END", youtubeId);
          resolve();
        });
    });
  });
};

//example array
const myArr = [
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
  "ficzsusamA0Mw",
];
(async () => {
  for (var i = 0; i < myArr.length; i++) {
    const imgUrl = `http://img.youtube.com/vi/${myArr[i]}/maxresdefault.jpg`;
    const options = url.parse(imgUrl);
    console.log("Going to call", myArr[i]);
    await callHttp(myArr[i], options);
    console.log("DOne ! ");
  }
})();
Related