0

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?

Eka
  • 14,170
  • 38
  • 128
  • 212

4 Answers4

2

Promise.all is your guy

Promise.all([
    browser.storage.sync.get('a1'),
    browser.storage.sync.get('a2')
]).then(([r1, r2]) => {
    // …
})

Unlike await this will do both requests simultaneously and wait until both are done before calling the function in .then.

Ben West
  • 4,398
  • 1
  • 16
  • 16
1

try async/await

async funciont name() {
    let b1 = (await browser.storage.sync.get('a1')).a1;
    let b2 = (await browser.storage.sync.get('a2')).a2;
}
林期斌
  • 11
  • 1
1

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']
});
erosman
  • 7,094
  • 7
  • 27
  • 46
0

Use async/await

const getb1 = async () => {
  let resp = (await browser.storage.sync.get('a1'));
  return resp.a1
}

const getb2 = async () => {
  let resp = (await browser.storage.sync.get('a2'));
  return resp.a2
}

or you can use Promise. all() if both are independent calls and wanted to run parallelly.

const getb1b2 = async () => {
  let [resp1,resp2] = await Promise.all([browser.storage.sync.get('a1'), browser.storage.sync.get('a2')]);
  let b1 = resp1.a1;
  let b2 = resp2.a2;
}