【发布时间】:2014-03-20 15:39:55
【问题描述】:
我正在开发一个使用 'chrome.storage.local' 的 chrome 扩展程序,并试图从 chrome.storage.local.get() 异步函数中创建一个承诺,我希望能够做到抛出异常以及拒绝/解决。我已尝试使用以下实现对此进行测试,但我看到控制台日志中出现的错误似乎来自“readLocalStorageObj("prefs").then(function(item) {”行(错误显示在代码后面)。
require([
"libs/bluebird"
],
function(Promise) {
function readLocalStorageObj(itemName) {
var localReadResult = Promise.method(function(item) {
console.log("localReadResult():", item);
// if (chrome.runtime.lastError) {
// throw new Error(chrome.runtime.lastError);
// }
if (Object.getOwnPropertyNames(item).length > 0) {
console.log('in if part');
return item;
}
else {
console.log('in else part');
// throw new Error("my test exception");
return undefined;
}
});
chrome.storage.local.get(itemName, localReadResult);
return localReadResult;
};
readLocalStorageObj("prefs").then(function(item) {
console.log('success', item);
}, function(e) {
console.log('fail', e);
}).error(function(e) {
console.log('error', e);
}).catch(ChromeRuntimeError, function(e) {
console.log('catch', e);
}).finally(function(a) {
console.log('finally', a);
});
});
错误:
未捕获的类型错误:对象函数 Promise$_method() { 变量值; 开关(参数。长度){ 案例 0:值 = tryCatch1(fn, this, void 0);休息; 案例 1: value = tryCatch1(fn, this, arguments[0]);休息; 案例......n'
我似乎无法弄清楚这是什么原因,并且非常感谢任何帮助。
TIA
【问题讨论】:
-
你想做什么?在这种情况下使用
Promise.method没有意义。 -
我基本上是在尝试从异步读取 chrome.storage API 中获取 Promise。关于在这种情况下如何获得 Promise 的任何其他建议?
标签: javascript google-chrome-extension requirejs bluebird