Wait for the variable to be completed

Asked

Viewed 191 times

2

Hello, I have the following array

[""Lucas", "pedro" ,"Joao"]

I need to submit a request with Xmlhttprequest for each name, then save the answer 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 the 3 var are filled, and only then call Function

I hear Promises can help me, someone has a solution?

1 answer

3


Yes, Promises in this case is useful. You can do this using Promise.all that waits for Promise to retrieve 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);
});

Browser other questions tagged

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