LocalStorage - Best Practice to Set Multiple Keys?

If I have more than one key/value to save, what’s the best practice. Currently I am just doing something like below, but this has got to be wrong? I am guessing a loop over an array, but then how do I know all of the values have been set, since they are promise based?

Cheers for any help you can give!

this.localStorage.ready().then(() => {
this.localStorage.set(‘customURL’, this.formCustomURL).then((val) => {
this.localStorage.set(‘customHost’, this.formCustomHost).then((val) => {
this.showAlert(‘Settings’, ‘Your settings have been saved.’, [‘OK’]);
});
});
}).catch((err) => {
this.showAlert(‘Error Saving’, ‘Could not save settings to device’, [‘OK’]);
});

You can chain your promises in one array and run your function once all are finished like this:

this.localStorage.ready().then(() => {
  let promises = [
    this.localStorage.set(‘customURL’, this.formCustomURL),
    this.localStorage.set(‘customHost’, this.formCustomHost)
  ];

  Promise.all(promises)
    .then(data => {
      this.showAlert(‘Settings’, ‘Your settings have been saved.’, [ ‘OK’ ]);
    });
}).catch((err) => {
  this.showAlert(‘Error Saving’, ‘Could not save settings to device’, [ ‘OK’ ]);
});

Saimon,

Nice! I hadn’t come across this technique before. I had seen Promise.all before, but I guess I didn’t fully understand it. Thanks for this :slight_smile:

Si

please provide me full code