Wait for variable completion

2

Hello, I have the following array

["lucas", "peter", "john"]

I need to send a request with XMLHttpRequest for each name, then save the response in json of the 3 in an object and call another function, the problem is that I do not know how to make the execution wait until all 3 var are fulfilled , and then call function

Hearing that Promises can help me, does anyone have a solution?

    
asked by anonymous 09.11.2017 / 06:41

1 answer

3

Yes, promises in this case is helpful. You can do this by using Promise.all that waits for Promise to fetch the data:

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);
});
    
09.11.2017 / 07:43