我使用Eddy's nativescript-secure-storage plugin将多个变量存储在设备存储(NativeScript应用程序)中 .
每次存储值的调用都会返回一个promise:
this.secureStorage = new SecureStorage();
secureStorage.set({
key: "foo",
value: "val1"
}).then(
function(success) {
//move on to the next one.
});
存储多个值后,我需要将应用程序导航到主视图,但需要确认值是否已成功存储 .
我怎样才能避免嵌套这些调用(这确实有效,但对于许多值不会很好):
this.secureStorage = new SecureStorage();
secureStorage.set({
key: "foo1",
value: "val1"
}).then(
function(success) {
secureStorage.set({
key: "foo2",
value: "val2"
}).then(
function(success) {
secureStorage.set({
key: "foo3",
value: "val3"
}).then(
function(success) {
//navigate to home view
});
});
});
3 回答
Per @johnrsharpe:
RezaRahmati的答案很可靠 .
另一种方法是将承诺转换为可观察的 .
这是顺序存储:
或
Promise.all(...)
的等效:您可以使用
Promise.all([array of promises])
或使用Typescript async / await