[Vuejs]-Calling async function multiple times in short time messes up shopping cart

0👍

It doesn’t make sense to add an item multiple times, so your function should not queue up calls. You need to ignore inputs while you’re processing in addItem().

let busy = false;
async function takesAWhile() {
    if (busy) {
        console.log('busy. ignoring you');
        return;
    }
    // do some stuff
    busy = true;
    console.log('starting hard stuff');
    await new Promise((resolve,reject)=>{
        setTimeout(resolve,1000);
    })
    console.log('done');
    busy = false;
}

takesAWhile();
takesAWhile();

0👍

I’ve run into the same issue many times in the past. A simple solution is just to disable the button right after it’s clicked and then enable it again once your API call is complete. If the call takes a long time, you can consider using a disable with a spinner.

<button :disabled="isDisabled" @click="addItem">add item</button>

Then in your handler you can do something like:

this.isDisabled = true;
await doExpensiveAPICall();
this.isDisabled = false;

Make sure your button[disabled] CSS does something reasonable to make your buttons look disabled.

Leave a comment