Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

meredevelopment's avatar

Async Await and Axios

Hi, I have a function that loops through an object, getting some data from an API for each item:

methods: {
    async getThingsForAllItems(){
        for (let item of this.added_items) {
            await axios.get('/api/v1/'+item.id)
            .then(response => {                    
                console.log('got thing called: '+response.data.data.name)
                this.added_things.push(response.data.data)
            })
            .catch(error => {
                this.errors = error.response.data
            })
        }
    },
}

At the API end, the 'thing' returned is marked as 'consumed' and must not be retrieve by a future request, hence the reason for needing to do this sequentially / async.

-The above works-

However I want to move the axios call to it's own function. When I do this the axios requests fire off synchronously, and many of the same 'things' get consumed before they can be marked as consumed at the API end. Here's what I've tried:

methods: {
    async getThingsForAllItems(){
        for (let item of this.added_items) {
            await this.getNextThing( item.id )
        }
    },

    getNextThing(id){ 
        axios.get('/api/v1/'+id) //TODO: add count
        .then(response => {                    
            console.log('got thing called: '+response.data.data.name)
            this.added_things.push(response.data.data)
        })
        .catch(error => {
            this.errors = error.response.data
        })
    },
}

-The above does not work-

Can ideas why? Better ways to do this? Any pointers appreciated.

0 likes
2 replies
JohnBraun's avatar
Level 33

Use this in await this.getNextThing( item.id ) and return the axios response from the getNextThing() method perhaps?

1 like
meredevelopment's avatar

Thank you! yes using return axios.get... worked. I already had this. in my actual code but forgot to include it in the example above.

Great! thanks!

Please or to participate in this conversation.