XMLHttpRequest Good example applied

-2

Hello, all right? I'll explain my doubt.

I have an array with multiple names to automate a list of clients and need to send one by one in a get request

Example site.com.br/api/cadastro/user/ > name

I need to go through the entire array, remove a name from it and get a get in the api, wait for the answer and move on to the next, and at the same time show a percentage type of how much is still missing to finish the array. p>

Thanks for the help:)

    
asked by anonymous 12.10.2017 / 13:44

1 answer

2

You need to break this down into steps to keep track of progress.

An example would be like this, using promises:

function ajax(nome) {
  return new Promise(function(resolve, reject) {
    var url = 'https://httpbin.org/get?text=' + nome;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var json = JSON.parse(xmlhttp.responseText);
        resolve(json);
      }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
  });
}

function processarPedidos(nomes, fn, cb) {
  var progress = document.querySelector('progress');
  progress.value = 0;

  (function processador(arr) {
    var proximo = arr.shift();
    if (!proximo) cb();
    else ajax(proximo).then(fn).then(function() {
    
      // atualizar a progress bar
      progress.value = 100 - (arr.length * 100 / nomes.length);
      // chamar o próximo
      processador(arr, fn, cb);
    }).catch(function(err) {
      console.log(err);
    });
  })(nomes.slice());
}

var nomes = ['João', 'Ana', 'Maria', 'Rita', 'António', 'Paula'];

processarPedidos(nomes, function(json) {
  console.log(json.args);
}, function() {
  console.log('100%!!');
})
<progress value="0" max="100"></progress>
    
12.10.2017 / 20:31