Xmlhttprequest Good example applied

Asked

Viewed 183 times

-2

Hello, all right? I’ll explain my question

I have a multi-name array to automate a customer list and need to send one by one on a get request

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

I need to go through the entire array, remove a name from it and get into the api, wait for the answer and move on to the next one, and at the same time show a kind of percentage of how much is left to finish the array.

Thanks for the help :)

1 answer

1


You need to break it down into steps to get control 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>

  • When I get home I’ll answer

  • It worked, the problem is that when the server does not recognize the client, I searched and found the "Promise.Reject", I need to use it to continue the queue ? if yes how can I apply this Function ? [Edit: I used resolve("error"); and the queue continued, it’s a good way to solve ?]

  • @Plan ok, and if he makes a mistake should still count to the progress? In this case it places the contents of then( here too .catch(function(err) {&#xA; console.log(err);&#xA; });

Browser other questions tagged

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