Make code that uses Promises work also on older browsers

Asked

Viewed 80 times

2

I recently asked that question:

Wait for the variable to be completed

The moderator Sergio helped me with the issue, but I’m still having problems with compatibility with old browsers. There is a way to accomplish this without using Promises and that runs on older browsers?

Follow 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 make a request in each name and saving the answer in an object, while the code continues running and doing other tasks, when all the answers are in an object the code triggers another function.

1 answer

1


You can do it 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 keep adding to the response array what is being received, in the right index using the i in the .forEach

Browser other questions tagged

You are not signed in. Login or sign up in order to post.