Search code examples
javascriptfirefoxpromisefirefox-addonfirefox-addon-webextensions

How to work with multiple values in multiple promises?


I am writing a firefox addon and I need to store some values using browser.storage.sync. I need to store and fetch multiple values using this method. I wrote a simple code which fetches the values

browser.storage.sync.get('a1').then(r1 => {    
    browser.storage.sync.get('a2').then(r2 =>{
        console.log(r1.a1);
        console.log(r2.a2);
    });    
});

The thing is I dont like this nested structure of the code. I want to do something like this

// return b1 and b2 as values
let b1 = browser.storage.sync.get('a1').then(r1 => {    
   return r1.a1;
});

let b2 = browser.storage.sync.get('a2').then(r2 =>{
    return r2.a2
});

The problem is the b1 and b2 itself are promises and I don't know how to return a value instead.

How to work with multiple values in multiple promises?


Solution

  • It is more efficient not to run multiple async functions, when not needed. Instead of getting values one by one, you can get them all once.

    1. Get them all
    browser.storage.local.get().then(result => {
      console.log(result.a1); // or result['a1']
      console.log(result.a2); // or result['a2']
    });
    
    1. Get only the ones needed (as also mentioned by wOxxOm)
    browser.storage.local.get(['a1', 'a2']).then(result => {
      console.log(result.a1); // or result['a1']
      console.log(result.a2); // or result['a2']
    });