0

I am storing multiple variables in device storage (NativeScript app) using Eddy's nativescript-secure-storage plugin.

Each call to store a value returns a promise:

this.secureStorage = new SecureStorage();
secureStorage.set({
  key: "foo",
  value: "val1"
}).then(
  function(success) {
    //move on to the next one.
});

After multiple values are stored, I need to navigate the app to the home view, but need to confirm the values were successfully stored first.

How can I avoid nesting these calls this (which does work but will not be pretty with many values):

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
    });
  });
});
lilbiscuit
  • 2,109
  • 6
  • 32
  • 53

3 Answers3

2

RezaRahmati's answer is solid.

Another way would be to convert the promises to observables.

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

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

Here is the sequential store:

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

Or the equivelent of Promise.all(...):

forkJoin(
   store('foo1', 'value1'), 
   store('foo2', 'value2'), 
   store('foo3', 'value3')
).subscribe(
   ([foo1, foo2, foo3])=> { /* Success */ },
   err => { /* Error */ }
)
Pearman
  • 1,068
  • 5
  • 14
0

You can use Promise.all([array of promises]) or using Typescript async/await

since you tag your question as Angular I assume you are using Typescript 1.7+, then you can use this way

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);
   }
}
Reza
  • 18,865
  • 13
  • 88
  • 163
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
    });
lilbiscuit
  • 2,109
  • 6
  • 32
  • 53