Noa*_*oam 2 promise async-await typescript
我有一个带有 save 方法的打字稿类,我希望下一次调用 save 方法仅在第一个调用完成后才会发生。想象一下以下情况:
count = 0;
async save() {
let x = this.count++;
console.log("start " + x);
await axios.post("***",{});
console.log("end " + x);
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下 - 当用户调用保存时,无需等待 - 第二个帖子可以在第一个帖子完成之前调用 - 导致各种问题。
我想出的解决方案是:
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);
});
}
Run Code Online (Sandbox Code Playgroud)
这是一个有效的解决方案,还是有更好的方法?
then这种最后一个承诺的模式是完全有效的。您当前遇到的唯一问题是错误处理。在您当前的代码中,如果一个请求失败,它将导致所有未来的请求失败。
更完整的解决方案是这样的:
lastSave = Promise.resolve();
count = 0;
async save() {
const savePromise = this.lastSave.then(async () => {
let x = this.count++;
console.log("start " + x);
await axios.post("***",{});
console.log("end " + x);
});
// wait but don't fail forever on errors
this.lastSave = savePromise.then(() => {}).catch(() => {});
// You also need to return the promise so callers can react
// to it. Note the lack of `.catch` here to not interfere with error handling
return await savePromise;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |