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

走远了吗. 提交于 2019-12-23 02:38:37

问题


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


回答1:


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(...);


来源:https://stackoverflow.com/questions/49847904/how-do-i-use-promise-all-with-chrome-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!