我正在使用Ionic平台的SQLStorage。 remove
函数返回一个Promise。在我的代码中,我需要删除多个值。当这些都完成后,我需要执行一些代码。
如何等待它们全部完成,然后执行回调函数?
代码:
removeAll() {
this.storage.remove(key1);
this.storage.remove(key2);
this.storage.remove(key3);
}
嵌套所有东西是一种不好的实践,因此我正在寻找一个合适的解决方案 :)
removeAll() {
return this.storage.remove(key1).then(() => {
this.storage.remove(key2).then(() => {
this.storage.remove(key3);
});
});
};
Promise.all
将立即拒绝(无论其余的 Promise 是否已经完成),并且then
将被跳过。如果您需要无论成功或失败都要运行doSomething()
,则需要单独使用catch
来返回一个Promise.resolve()
。 - Manu ValdésPromise.all()
,它们是一个接一个地执行还是同时执行? - RoboustePromise.all()
只是等待所有这些 promise 完成之后再完成它自己。这不是一个Promise.all
特性。使用这段代码Promise.all([ this.storage.remove(key1),
, ...]);会调用
this.storage.remove(key1),只有返回值(一个
Promise)被添加到传递给
Promise.all(...)` 的数组中。 - Günter Zöchbauer