Make code that uses Promises to work also in older browsers

2

Recently I asked this question:

Wait for variable completion

Moderator Sergio helped me with the issue, but I'm still having issues with compatibility with legacy browsers. Is there a way to accomplish this without using Promises and running on older browsers?

Here is the example code:

function getNome(nome) {
  const url = 'https://httpbin.org/get?nome=' + nome;
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = function() {
      if (xhr.status === 200) resolve(JSON.parse(xhr.responseText));
      else reject(xhr.status);
    };
    xhr.send();
  });
}

const nomes = ["lucas", "pedro", "joao"];
Promise.all(nomes.map(getNome)).then(res => {
  console.log(res);
});

What I want is to go through an array, and perform a request on each name and save the response on an object, meanwhile the code keeps on running and doing other tasks, when all the answers are in an object the code fires another function.

    
asked by anonymous 12.11.2017 / 05:56

1 answer

1

You can do this with callbacks like this:

function getNome(nome, cb) {
  const url = 'https://httpbin.org/get?nome=' + nome;
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = function() {
    if (xhr.status === 200) cb(null, JSON.parse(xhr.responseText));
    else cb(xhr.status);
  };
  xhr.send();
}

function processador(arr, done) {
  var respostas = [];
  var total = arr.length;
  arr.forEach(function(el, i) {
    getNome(el, function(err, res) {
      if (err) done(err);
      respostas[i] = res;
      total--;
      if (total == 0) done(null, respostas);
    })
  });
}

const nomes = ["lucas", "pedro", "joao"];
processador(nomes, function(err, res) {
  if (err) console.log(err);
  else console.log(res);
});

The idea is to manage responses with functions ( callbacks ) and add the response array to the response array received at the right index using i no .forEach

    
12.11.2017 / 09:48