|
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/. */ |
|
4 |
|
5 let EXPORTED_SYMBOLS = [ |
|
6 "AsyncRunner", |
|
7 ]; |
|
8 |
|
9 const { interfaces: Ci, classes: Cc } = Components; |
|
10 |
|
11 function AsyncRunner(callbacks) { |
|
12 this._callbacks = callbacks; |
|
13 this._iteratorQueue = []; |
|
14 |
|
15 // This catches errors reported to the console, e.g., via Cu.reportError. |
|
16 Cc["@mozilla.org/consoleservice;1"]. |
|
17 getService(Ci.nsIConsoleService). |
|
18 registerListener(this); |
|
19 } |
|
20 |
|
21 AsyncRunner.prototype = { |
|
22 |
|
23 appendIterator: function AR_appendIterator(iter) { |
|
24 this._iteratorQueue.push(iter); |
|
25 }, |
|
26 |
|
27 next: function AR_next(/* ... */) { |
|
28 if (!this._iteratorQueue.length) { |
|
29 this.destroy(); |
|
30 this._callbacks.done(); |
|
31 return; |
|
32 } |
|
33 |
|
34 // send() discards all arguments after the first, so there's no choice here |
|
35 // but to send only one argument to the yielder. |
|
36 let args = [arguments.length <= 1 ? arguments[0] : Array.slice(arguments)]; |
|
37 try { |
|
38 var val = this._iteratorQueue[0].send.apply(this._iteratorQueue[0], args); |
|
39 } |
|
40 catch (err if err instanceof StopIteration) { |
|
41 this._iteratorQueue.shift(); |
|
42 this.next(); |
|
43 return; |
|
44 } |
|
45 catch (err) { |
|
46 this._callbacks.error(err); |
|
47 } |
|
48 |
|
49 // val is truthy => call next |
|
50 // val is an iterator => prepend it to the queue and start on it |
|
51 if (val) { |
|
52 if (typeof(val) != "boolean") |
|
53 this._iteratorQueue.unshift(val); |
|
54 this.next(); |
|
55 } |
|
56 }, |
|
57 |
|
58 destroy: function AR_destroy() { |
|
59 Cc["@mozilla.org/consoleservice;1"]. |
|
60 getService(Ci.nsIConsoleService). |
|
61 unregisterListener(this); |
|
62 this.destroy = function AR_alreadyDestroyed() {}; |
|
63 }, |
|
64 |
|
65 observe: function AR_consoleServiceListener(msg) { |
|
66 if (msg instanceof Ci.nsIScriptError && |
|
67 !(msg.flags & Ci.nsIScriptError.warningFlag)) |
|
68 { |
|
69 this._callbacks.consoleError(msg); |
|
70 } |
|
71 }, |
|
72 }; |