[Vuejs]-Asynchronous pushing of values to an array in Vue.js

0👍

You actually do not need async/await at all in fetchContactPostById since there’s only one asynchronous method used, and it returns a Promise

What you need to do is return this.$http.get(.... and then remove all the async and await keywords

fetchContactPostById: function (postId) {
    return this.$http.get(this.baseUrl + '/wp-json/acf/v3/contacts-api/' + postId)
    .then(response => {
        response.data.acf.id = postId;
        let result = this.contacts.push(response.data);
        return result;
    }).catch(e => {
        this.errors.push(e);
    })
},

as an aside – the return result – do you understand it returns a number (the new length of the array) and the calling code assigns this value but never actually uses it?

the streamlined code would be

this.$http.get(this.baseUrl + '/wp-json/wp/v2/pages?slug=' + menuChildSlug).then(async response => {
      this.page = response.data[0];
      this.pageSections = this.page.acf.sections;
      this.contactSections = this.page.acf.contacts;
      for (let contact of this.contactSections) {
        await this.fetchContactPostById(contact.add_contact.ID);
      }
}).catch(e => {
    this.errors.push(e)
})

and

fetchContactPostById: function (postId) {
    return this.$http.get(this.baseUrl + '/wp-json/acf/v3/contacts-api/' + postId)
    .then(response => {
        response.data.acf.id = postId;
        this.contacts.push(response.data);
    }).catch(e => {
        this.errors.push(e);
    })
},

0👍

You call your data in a certain order, but the response will eventually be received in a different order.
(Depending on how your server will respond, thats’ why the call is asynchronous).
If you want to keep the same order in your second array, you have to send the index of the first array to your second one.

Leave a comment