Eva*_*van 5 javascript google-chrome async-await bluebird
我正在尝试使用 Bluebird.js 来保证 chrome.storage.sync.get 。我看到 bluebird http://bluebirdjs.com/docs/working-with-callbacks.html站点上的所有示例都使用Promise.promisify(require(someAPI)). 我尝试做
const storageGet = Promise.promisify(chrome.storage.sync.get);(如果这会影响任何事情,我没有要求),然后调用
async function() {
return await storageGet('config', function (result) {
// do stuff
})
};
Run Code Online (Sandbox Code Playgroud)
控制台错误是
Unhandled rejection Error: Invocation of form get(string, function, function)
doesn't match definition get(optional string or array or object keys, function
callback)
Run Code Online (Sandbox Code Playgroud)
我的理解(对 Promises 和 bluebird 的理解很少)是 storageGet 传递了错误的参数?但是 chrome.storage.sync.get 需要传递一个字符串和一个回调函数,所以我不是特别确定出了什么问题。此外,我可能完全不知道如何承诺 chrome 存储。
我知道http://bluebirdjs.com/docs/api/promise.promisifyall.html#option-promisifier有一个关于 chrome promisifying 的例子,但老实说,我对 promise 不太熟悉,无法理解发生了什么那个例子。
是否有某种方式我应该承诺 chrome 存储而不是我这样做的方式?
您想要使用 Bluebird 承诺的函数的回调 API 必须符合 NodeJS 回调约定:“错误优先,单参数”(如此处所述)。根据存储同步文档,其 API 不符合 Bluebird 的要求:
StorageArea.get(string or array of string or object keys, function callback)
/* Callback with storage items, or on failure (in which case runtime.lastError will be set).
The callback parameter should be a function that looks like this:
function(object items) {...};*/
Run Code Online (Sandbox Code Playgroud)
根本没有错误参数。这个方法甚至没有抛出任何错误。它仅公开结果。您可以通过将给定方法包装为以下方式轻松将其转换为基于 Promise 的 API Promise:
function getFromStorageSync(key) {
return new Promise(function(resolve) {
chrome.storage.sync.get(key, function(items) {
resolve(items)
})
})
}
getFromStorageSync('someKey').then(function(items) { console.log(items) })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
778 次 |
| 最近记录: |