0

Given the following Vue method to call an API using Axios to fetch some data:

fetch: function() {

    console.log('Commence call to API!');

    axios.get("fetch.php")
        .then(response => {

            if (response.status === 204) {
                this.noContent = true;
            } else {
                console.log(response.data);
            }                    
        });

    console.log('Method complete!');                    
},

The expected in the console output should be as follows:

  1. Commence call to API!
  2. {{Some response data}}
  3. Method complete!

Instead, what often happens is the following:

  1. Commence call to API!
  2. Method complete!
  3. {{Some response data}}

How can I ensure that the method behaves in a 'sequential' manner?

chivano
  • 603
  • 1
  • 5
  • 13
  • [How do I set a specific order of execution when asynchronous calls are involved?](https://stackoverflow.com/questions/30497968/how-do-i-set-a-specific-order-of-execution-when-asynchronous-calls-are-involved) | The answer talks about `setTimeout`, but the concept is the same as an AJAX request. – yuriy636 Jan 24 '18 at 13:43
  • Well it still deserve some explanation why axios is asynchronous using Promise. – mathk Jan 24 '18 at 13:53
  • 2
    There must be thousands of answers that explain the asynchronous nature of promises and AJAX. I dupe hammered this with one that has long, reasonable explanations, including two additional links on how to structure asynchronous code in the very first answer. – Bert Jan 24 '18 at 13:59
  • Yes the question you suggest seems to be very details on that subject but for a beginner it might not be obvious how is it related to `axios` ? – mathk Jan 24 '18 at 14:08

0 Answers0