在Angular中避免嵌套的promise

时间:2018-05-04 19:57:56

标签: angular nativescript angular-promise

我使用Eddy's nativescript-secure-storage plugin在设备存储(NativeScript app)中存储多个变量。

每次存储值的调用都会返回一个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 个答案:

答案 0 :(得分:1)

RezaRahmati的答案很可靠。

另一种方法是将promises转换为observable。

import { fromPromise } from 'rxjs/observable/fromPromise';
import { mergeMap } from 'rxjs/operators';

const secureStorage = new SecureStorage();
const store = (key, value) => fromPromise(secureStorage.set({key, value}));

这是顺序存储:

store('foo1', 'value1')
   .pipe(
       mergeMap(() => store('foo2', 'value2')),
       mergeMap(() => store('foo3', 'value3'))
   ).subscribe(
      () =>  {/* Handle success */ }, 
      err => {/* Handle error*/ }
   )

或等同于Promise.all(...)

forkJoin(
   store('foo1', 'value1'), 
   store('foo2', 'value2'), 
   store('foo3', 'value3')
).subscribe(
   ([foo1, foo2, foo3])=> { /* Success */ },
   err => { /* Error */ }
)

答案 1 :(得分:0)

您可以使用Promise.all([array of promises])或使用Typescript async / await

  

因为您将问题标记为Angular我假设您使用的是Typescript 1.7+,那么您可以使用这种方式

async storedata() {

   this.secureStorage = new SecureStorage();

   try {
     await secureStorage.set({
        key: "foo1",
        value: "val1"
     });
     await secureStorage.set({
        key: "foo2",
        value: "val2"
     });
     await secureStorage.set({
        key: "foo3",
        value: "val3"
     });

    //navigate to home view

   } catch(err) {
       console.error(err);
   }
}

答案 2 :(得分:0)

Per @johnrsharpe:

Promise 
    .all( [
        this.secureStorage.set({
           key: "foo1",
           value: "value1"
        }),
        this.secureStorage.set({
           key: "foo2",
           value: "value2"
        }),
        this.secureStorage.set({
           key: "foo3",
           value: "value3"
        })
    ])
    .then(success => {
        //navigate to home view
    });