Index: extensions/renderer/resources/utils.js |
diff --git a/extensions/renderer/resources/utils.js b/extensions/renderer/resources/utils.js |
index 803a3518d753b271bf740dd982d51d8af86c4720..4420c618a96a35e9f8f79235a2ebd658e63ccd82 100644 |
--- a/extensions/renderer/resources/utils.js |
+++ b/extensions/renderer/resources/utils.js |
@@ -6,6 +6,7 @@ var createClassWrapper = requireNative('utils').createClassWrapper; |
var nativeDeepCopy = requireNative('utils').deepCopy; |
var schemaRegistry = requireNative('schema_registry'); |
var CHECK = requireNative('logging').CHECK; |
+var DCHECK = requireNative('logging').DCHECK; |
var WARNING = requireNative('logging').WARNING; |
/** |
@@ -133,8 +134,41 @@ function deepCopy(value) { |
return nativeDeepCopy(value); |
} |
+/** |
+ * Wrap an asynchronous API call to a function |func| in a promise. The |
+ * remaining arguments will be passed to |func|. Returns a promise that will be |
+ * resolved to the result passed to the callback or rejected if an error occurs |
+ * (if chrome.runtime.lastError is set). If there are multiple results, the |
+ * promise will be resolved with an array containing those results. |
+ * |
+ * For example, |
+ * promise(chrome.storage.get, 'a').then(function(result) { |
+ * // Use result. |
+ * }).catch(function(error) { |
+ * // Report error.message. |
+ * }); |
+ */ |
+function promise(func) { |
+ var args = $Array.slice(arguments, 1); |
+ DCHECK(typeof func == 'function'); |
+ return new Promise(function(resolve, reject) { |
+ args.push(function() { |
+ if (chrome.runtime.lastError) { |
+ reject(new Error(chrome.runtime.lastError)); |
+ return; |
+ } |
+ if (arguments.length <= 1) |
+ resolve(arguments[0]); |
+ else |
+ resolve($Array.slice(arguments)); |
+ }); |
+ $Function.apply(func, null, args); |
+ }); |
+} |
+ |
exports.forEach = forEach; |
exports.loadTypeSchema = loadTypeSchema; |
exports.lookup = lookup; |
exports.expose = expose; |
exports.deepCopy = deepCopy; |
+exports.promise = promise; |