My TypeScript class has a save method that I want to only let the next call happen once the first one is completed. Consider this scenario:
count = 0;
async save() {
let x = this.count++;
console.log("start " + x);
await axios.post("***", {});
console.log("end " + x);
}
}
In this situation, if the user calls save without awaiting it, the second post can be made before the first one completes, leading to potential issues.
The solution I have come up with is:
lastSave = Promise.resolve();
count = 0;
async save() {
this.lastSave = this.lastSave.then(async () => {
let x = this.count++;
console.log("start " + x);
await axios.post("***", {});
console.log("end " + x);
});
}
Is this approach valid, or is there a better way to achieve the desired outcome?