如何将Promise.all()与chrome.storage()结合使用? [英] How do I use Promise.all() with chrome.storage()?

查看:94
本文介绍了如何将Promise.all()与chrome.storage()结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个异步功能正在运行.我想等他们全部完成再采取下一步.这是我用来从chrome.storagePromise.all()实现中获取所有键/值的代码.

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]
});

不幸的是,这行不通.返回undefined.

This doesn't work unfortunately. It returns undefined.

上面的大多数代码均来自MDN,网址为:

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

推荐答案

chrome.* API不支持promise,它使用异步回调.
但是您可以拨通chrome.storage.sync.get的电话:

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

这篇关于如何将Promise.all()与chrome.storage()结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆