alexlee11111
alexlee11111

Reputation: 109

How to wait for the response before running the rest of the code?

I would like to run a loop of axios request calling backend, and wait for all the responses before redirecting the page.

In the following code, once I receive a response of 200 OK, I want to push it to the promiseArray. If I receive all promiseArray item, I would like to redirect the page to another url.

For my case, it seems that the code don't really stop to wait for the response. it loop for the axios request for 3 times, but instead of waiting the response, it directly run the redirecting section.

Any idea?

 function test(){
  var response = undefined;
  var length = 3;
  var promiseArray = [];

  for(var a=0;a<length;a++){

        var link = 'https://'+hostname+'/';
        var apiUrl = 'api/xxx';
        var token = "123";

        axios.create({
            baseURL: link,
            timeout: 60000,
            headers: {
            Authorization: token
            }
        }).post(apiUrl, {
            ...
        }).then(res => {
            console.log(res);
            promiseArray.push(res);
        }).catch(err=>{
            console.log("err");
            console.log(err);
        });
  }


  response = await axios.all(promiseArray);
  if(response!=undefined){
      window.location.replace("https://"+hostname+"/abc");
  }
}

Upvotes: 1

Views: 2414

Answers (3)

Gaurav Punjabi
Gaurav Punjabi

Reputation: 153

If you're already using async / await in one place, why not use it everywhere:

 async function test(){
  var length = 3;

  for(var a=0; a<length; a++){

        var link = 'https://'+hostname+'/';
        var apiUrl = 'api/xxx';
        var token = "123";

        let res = await axios.create({
            baseURL: link,
            timeout: 60000,
            headers: {
                Authorization: token
            }
        }).post(apiUrl, {
            ...
        });
        /* Do whatever you need with res */
  }
  window.location.replace("https://"+hostname+"/abc");
}

Upvotes: 0

tarek hassan
tarek hassan

Reputation: 802

You would like to wait all responses before redirecting the page, so what you need is to use Promise.all()

This following example from MDN

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

Upvotes: 0

Tim VN
Tim VN

Reputation: 1193

That's because promiseArray is empty, you're pushing the results to it. Push the actual promises to the array.

async function test(){
  var response = undefined;
  var length = 3;
  var promiseArray = [];

  for(var a=0;a<length;a++){

        var link = 'https://'+hostname+'/';
        var apiUrl = 'api/xxx';
        var token = "123";

        promiseArray.push(
            axios.create({
                baseURL: link,
                timeout: 60000,
                headers: {
                Authorization: token
                }
            }).post(apiUrl, {
                ...
            })
        )
  }


  response = await axios.all(promiseArray);
  if(response!=undefined){
      window.location.replace("https://"+hostname+"/abc");
  }
}

Upvotes: 1

Related Questions