E
E
EVOSandru62018-04-02 06:58:50
Vue.js
EVOSandru6, 2018-04-02 06:58:50

How to intercept asynchronous request data using axios without setTimeout() in Vue2?

Good afternoon,
There is such a problem. By http request I pull out data from the server for initial initialization. But there is a problem at runtime - the data that comes in responses cannot be intercepted due to the asynchrony of such requests.
The example reflects my problem. Simplified as much as possible for clarity.

export default {

        data: function () {
            return {
                order: null,
            }
        },
        created() {

            this.initOrder();

            this.initOptions();
        },

        methods: {

            initOrder() {

                HTTP.get('/orders/id=' + this.$route.params.id).then((response) =>
                {

                    this.order = response.data;
                });
            },
            initOptions() {

                console.log(this.order); // return null

                // ...

                this.order.param = 'oops'; // exception cannot read property of null

                // ...

                setTimeout(() => {

                    console.log(this.order); // return expected object

                    this.order.param = 'oops'; // so good by setTimeout is cumbersome

                }, 1000);
            }
        },
    }

}

Interested - how to solve this problem as a last resort by killing asynchrony or something else humanly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2018-04-02
@EVOSandru6

Gotta do it like this

data: function () {
            return {
                order: {
                  param: 'default state'
                },
            }
        },

and there will be no exception. Those. for all parameters, the structure should be described in advance.
Plus, in a good way, asynchronous methods should return a promise
initOrder() {
  return HTTP.get('/orders/id=' + this.$route.params.id)
    .then((response) => {
      this.loaded = true;
      this.order = response.data;
    });
},

Now we can always hang up some action on the initOrder resolution through then, for example, call initOptions. And on the main component, using the this.loaded flag, you can show some kind of twist until the data is loaded. A promise can also be returned by making it, well, rewriting it as an async function.
async initOrder()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question