Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Promise.all() with chrome.storage()?

I have several async functions running. I want to wait for them all to finish before taking the next steps. Here's my code that I'm using to get all of the key/values from chrome.storage and the Promise.all() implementation.

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, 'foo');
});

var getAll = chrome.storage.sync.get(function(result) {
  console.log(result)
});

Promise.all([promise1, promise2, promise3, getAll]).then(function(values) {
  console.log(values); // [3, 42, "foo", undefined]
});

This doesn't work unfortunately. It returns undefined.

Most of the code above is taken from MDN here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

like image 958
jkupczak Avatar asked Apr 15 '18 23:04

jkupczak


People also ask

How to use promise all()?

all() The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.

Does promise all resolve in order?

The chronological order of resolution does absolutely not matter when all promises fulfill. The order of values in the result array is the same as in the input array of promises.

Can a Chrome extension use local storage?

You can call localStorage directly from the options page or use chrome. extension.

How do I find Chrome Sync storage?

With the extension's background page open, just go to the developer tools by pressing F12, then go to the Application tab. In the Storage section expand Local Storage. After that, you'll see all your browser's local storage there.


1 Answers

The chrome.* API does not support promises, it uses async callbacks.
But you can promisify your call to chrome.storage.sync.get:

var getAllPromise = (function() {
    return new Promise(function(resolve) {
        chrome.storage.sync.get(function(result) {
            resolve(result);
        });
    });
})();

Promise.all([getAllPromise]).then(...);
like image 152
Denis L Avatar answered Sep 28 '22 23:09

Denis L