繁体   English   中英

使用Bluebird Promisify chrome API

[英]Promisify chrome API using 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
  })
};

控制台错误是

Unhandled rejection Error: Invocation of form get(string, function, function) 
doesn't match definition get(optional string or array or object keys, function 
callback)

我的理解(对Promises和bluebird缺乏了解)是storageGet传递了错误的参数吗? 但是chrome.storage.sync.get需要传递一个字符串和一个回调函数,所以我不太确定会出现什么问题。 此外,我可以完全放弃我如何宣传镀铬存储。

我知道在http://bluebirdjs.com/docs/api/promise.promisifyall.html#option-promisifier上有一个chrome promisifying的例子,但老实说我不太熟悉承诺,了解发生了什么那个例子。

我应该以某种方式宣传镀铬存储而不是我正在做的方式吗?

要与蓝鸟到promisify的回调函数API必须符合回调的NodeJS约定:“错误一,单参数”(如说HERE )。 根据存储同步文档,其API不符合Bluebird要求的API:

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) {...};*/

根本没有错误参数。 这种方法甚至没有抛出任何错误。 它只公开结果。 通过使用Promise包装给定方法,您可以轻松将其转换为基于Promise的API:

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

更通用,并在设置chrome.runtime.lastError时捕获错误。

/**
 * Converts asynchronous chrome api based callbacks to promises
 *
 * @param {function} fn
 * @param {arguments} arguments to function
 * @returns {Promise} Pending promise returned by function
 */
var promisify = function (fn) {
  var args = Array.prototype.slice.call(arguments).slice(1);
  return new Promise(function(resolve, reject) {
    fn.apply(null, args.concat(function (res) {
      if (chrome.runtime.lastError) {
        return reject(chrome.runtime.lastError);
      }
      return resolve(res);
    }));
  });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM