1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 const EXPORTED_SYMBOLS = ["Async"];
7 const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
9 // Constants for makeSyncCallback, waitForSyncCallback.
11 const CB_COMPLETE = {};
14 const REASON_ERROR = Ci.mozIStorageStatementCallback.REASON_ERROR;
16 Cu.import("resource://gre/modules/Services.jsm");
19 * Helpers for various async operations.
24 * Execute an arbitrary number of asynchronous functions one after the
25 * other, passing the callback arguments on to the next one. All functions
26 * must take a callback function as their last argument. The 'this' object
27 * will be whatever chain()'s is.
29 * @usage this._chain = Async.chain;
30 * this._chain(this.foo, this.bar, this.baz)(args, for, foo)
32 * This is equivalent to:
35 * self.foo(args, for, foo, function (bars, args) {
36 * self.bar(bars, args, function (baz, params) {
37 * self.baz(baz, params);
41 chain: function chain() {
42 let funcs = Array.slice(arguments);
44 return function callback() {
46 let args = Array.slice(arguments).concat(callback);
47 let f = funcs.shift();
48 f.apply(thisObj, args);
54 * Helpers for making asynchronous calls within a synchronous API possible.
56 * If you value your sanity, do not look closely at the following functions.
60 * Create a sync callback that remembers state, in particular whether it has
63 makeSyncCallback: function makeSyncCallback() {
64 // The main callback remembers the value it was passed, and that it got data.
65 let onComplete = function onComplete(data) {
66 onComplete.state = CB_COMPLETE;
67 onComplete.value = data;
70 // Initialize private callback data in preparation for being called.
71 onComplete.state = CB_READY;
72 onComplete.value = null;
74 // Allow an alternate callback to trigger an exception to be thrown.
75 onComplete.throw = function onComplete_throw(data) {
76 onComplete.state = CB_FAIL;
77 onComplete.value = data;
79 // Cause the caller to get an exception and stop execution.
87 * Wait for a sync callback to finish.
89 waitForSyncCallback: function waitForSyncCallback(callback) {
90 // Grab the current thread so we can make it give up priority.
91 let thread = Cc["@mozilla.org/thread-manager;1"].getService().currentThread;
93 // Keep waiting until our callback is triggered (unless the app is quitting).
94 while (Async.checkAppReady() && callback.state == CB_READY) {
95 thread.processNextEvent(true);
98 // Reset the state of the callback to prepare for another call.
99 let state = callback.state;
100 callback.state = CB_READY;
102 // Throw the value the callback decided to fail with.
103 if (state == CB_FAIL) {
104 throw callback.value;
107 // Return the value passed to the callback.
108 return callback.value;
112 * Check if the app is still ready (not quitting).
114 checkAppReady: function checkAppReady() {
115 // Watch for app-quit notification to stop any sync calls
116 Services.obs.addObserver(function onQuitApplication() {
117 Services.obs.removeObserver(onQuitApplication, "quit-application");
118 Async.checkAppReady = function() {
119 throw Components.Exception("App. Quitting", Cr.NS_ERROR_ABORT);
121 }, "quit-application", false);
122 // In the common case, checkAppReady just returns true
123 return (Async.checkAppReady = function() { return true; })();
127 * Return the two things you need to make an asynchronous call synchronous
128 * by spinning the event loop.
130 makeSpinningCallback: function makeSpinningCallback() {
131 let cb = Async.makeSyncCallback();
132 function callback(error, ret) {
137 callback.wait = function() Async.waitForSyncCallback(cb);
141 // Prototype for mozIStorageCallback, used in querySpinningly.
142 // This allows us to define the handle* functions just once rather
143 // than on every querySpinningly invocation.
144 _storageCallbackPrototype: {
147 // These are set by queryAsync.
151 handleResult: function handleResult(results) {
159 while ((row = results.getNextRow()) != null) {
161 for each (let name in this.names) {
162 item[name] = row.getResultByName(name);
164 this.results.push(item);
167 handleError: function handleError(error) {
168 this.syncCb.throw(error);
170 handleCompletion: function handleCompletion(reason) {
172 // If we got an error, handleError will also have been called, so don't
173 // call the callback! We never cancel statements, so we don't need to
174 // address that quandary.
175 if (reason == REASON_ERROR)
178 // If we were called with column names but didn't find any results,
179 // the calling code probably still expects an array as a return value.
180 if (this.names && !this.results) {
183 this.syncCb(this.results);
187 querySpinningly: function querySpinningly(query, names) {
188 // 'Synchronously' asyncExecute, fetching all results by name.
189 let storageCallback = {names: names,
190 syncCb: Async.makeSyncCallback()};
191 storageCallback.__proto__ = Async._storageCallbackPrototype;
192 query.executeAsync(storageCallback);
193 return Async.waitForSyncCallback(storageCallback.syncCb);