parallel execution

by Artem

JavaScript

'use strict';

function downloadAsync(url, onsuccess, onerror) {
  setTimeout(() => {
    onsuccess(url);
    // onerror('404');
  }, 1000);
}

function downloadAllAsync(urls, onsuccess, onerror) {
  var pending = urls.length;
  var result = [];

  if (pending === 0) {
    setTimeout(onsuccess.bind(null, result), 0);
    return;
  }

  urls.forEach((url, i) => {
    downloadAsync(url, (text) => {
      if (result) {
        result[i] = text;
        pending--;
        if (pending === 0) {
          onsuccess(result);
        }
      }
    }, (error) => {
      if (result) {
        result = null;
        onerror(result);
      }
    });
  });
}

downloadAllAsync(
  ['url1', 'url2'],
  (result) => {
    console.log(result);
  },
  (error) => {
    console.log(error);
  }
);