toolkit/modules/Task.jsm

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
michael@0 2 /* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */
michael@0 3 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
michael@0 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 6
michael@0 7 "use strict";
michael@0 8
michael@0 9 this.EXPORTED_SYMBOLS = [
michael@0 10 "Task"
michael@0 11 ];
michael@0 12
michael@0 13 /**
michael@0 14 * This module implements a subset of "Task.js" <http://taskjs.org/>.
michael@0 15 *
michael@0 16 * Paraphrasing from the Task.js site, tasks make sequential, asynchronous
michael@0 17 * operations simple, using the power of JavaScript's "yield" operator.
michael@0 18 *
michael@0 19 * Tasks are built upon generator functions and promises, documented here:
michael@0 20 *
michael@0 21 * <https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators>
michael@0 22 * <http://wiki.commonjs.org/wiki/Promises/A>
michael@0 23 *
michael@0 24 * The "Task.spawn" function takes a generator function and starts running it as
michael@0 25 * a task. Every time the task yields a promise, it waits until the promise is
michael@0 26 * fulfilled. "Task.spawn" returns a promise that is resolved when the task
michael@0 27 * completes successfully, or is rejected if an exception occurs.
michael@0 28 *
michael@0 29 * -----------------------------------------------------------------------------
michael@0 30 *
michael@0 31 * Cu.import("resource://gre/modules/Task.jsm");
michael@0 32 *
michael@0 33 * Task.spawn(function* () {
michael@0 34 *
michael@0 35 * // This is our task. Let's create a promise object, wait on it and capture
michael@0 36 * // its resolution value.
michael@0 37 * let myPromise = getPromiseResolvedOnTimeoutWithValue(1000, "Value");
michael@0 38 * let result = yield myPromise;
michael@0 39 *
michael@0 40 * // This part is executed only after the promise above is fulfilled (after
michael@0 41 * // one second, in this imaginary example). We can easily loop while
michael@0 42 * // calling asynchronous functions, and wait multiple times.
michael@0 43 * for (let i = 0; i < 3; i++) {
michael@0 44 * result += yield getPromiseResolvedOnTimeoutWithValue(50, "!");
michael@0 45 * }
michael@0 46 *
michael@0 47 * return "Resolution result for the task: " + result;
michael@0 48 * }).then(function (result) {
michael@0 49 *
michael@0 50 * // result == "Resolution result for the task: Value!!!"
michael@0 51 *
michael@0 52 * // The result is undefined if no value was returned.
michael@0 53 *
michael@0 54 * }, function (exception) {
michael@0 55 *
michael@0 56 * // Failure! We can inspect or report the exception.
michael@0 57 *
michael@0 58 * });
michael@0 59 *
michael@0 60 * -----------------------------------------------------------------------------
michael@0 61 *
michael@0 62 * This module implements only the "Task.js" interfaces described above, with no
michael@0 63 * additional features to control the task externally, or do custom scheduling.
michael@0 64 * It also provides the following extensions that simplify task usage in the
michael@0 65 * most common cases:
michael@0 66 *
michael@0 67 * - The "Task.spawn" function also accepts an iterator returned by a generator
michael@0 68 * function, in addition to a generator function. This way, you can call into
michael@0 69 * the generator function with the parameters you want, and with "this" bound
michael@0 70 * to the correct value. Also, "this" is never bound to the task object when
michael@0 71 * "Task.spawn" calls the generator function.
michael@0 72 *
michael@0 73 * - In addition to a promise object, a task can yield the iterator returned by
michael@0 74 * a generator function. The iterator is turned into a task automatically.
michael@0 75 * This reduces the syntax overhead of calling "Task.spawn" explicitly when
michael@0 76 * you want to recurse into other task functions.
michael@0 77 *
michael@0 78 * - The "Task.spawn" function also accepts a primitive value, or a function
michael@0 79 * returning a primitive value, and treats the value as the result of the
michael@0 80 * task. This makes it possible to call an externally provided function and
michael@0 81 * spawn a task from it, regardless of whether it is an asynchronous generator
michael@0 82 * or a synchronous function. This comes in handy when iterating over
michael@0 83 * function lists where some items have been converted to tasks and some not.
michael@0 84 */
michael@0 85
michael@0 86 ////////////////////////////////////////////////////////////////////////////////
michael@0 87 //// Globals
michael@0 88
michael@0 89 const Cc = Components.classes;
michael@0 90 const Ci = Components.interfaces;
michael@0 91 const Cu = Components.utils;
michael@0 92 const Cr = Components.results;
michael@0 93
michael@0 94 Cu.import("resource://gre/modules/Promise.jsm");
michael@0 95
michael@0 96 // The following error types are considered programmer errors, which should be
michael@0 97 // reported (possibly redundantly) so as to let programmers fix their code.
michael@0 98 const ERRORS_TO_REPORT = ["EvalError", "RangeError", "ReferenceError", "TypeError"];
michael@0 99
michael@0 100 /**
michael@0 101 * Detect whether a value is a generator.
michael@0 102 *
michael@0 103 * @param aValue
michael@0 104 * The value to identify.
michael@0 105 * @return A boolean indicating whether the value is a generator.
michael@0 106 */
michael@0 107 function isGenerator(aValue) {
michael@0 108 return Object.prototype.toString.call(aValue) == "[object Generator]";
michael@0 109 }
michael@0 110
michael@0 111 ////////////////////////////////////////////////////////////////////////////////
michael@0 112 //// Task
michael@0 113
michael@0 114 /**
michael@0 115 * This object provides the public module functions.
michael@0 116 */
michael@0 117 this.Task = {
michael@0 118 /**
michael@0 119 * Creates and starts a new task.
michael@0 120 *
michael@0 121 * @param aTask
michael@0 122 * - If you specify a generator function, it is called with no
michael@0 123 * arguments to retrieve the associated iterator. The generator
michael@0 124 * function is a task, that is can yield promise objects to wait
michael@0 125 * upon.
michael@0 126 * - If you specify the iterator returned by a generator function you
michael@0 127 * called, the generator function is also executed as a task. This
michael@0 128 * allows you to call the function with arguments.
michael@0 129 * - If you specify a function that is not a generator, it is called
michael@0 130 * with no arguments, and its return value is used to resolve the
michael@0 131 * returned promise.
michael@0 132 * - If you specify anything else, you get a promise that is already
michael@0 133 * resolved with the specified value.
michael@0 134 *
michael@0 135 * @return A promise object where you can register completion callbacks to be
michael@0 136 * called when the task terminates.
michael@0 137 */
michael@0 138 spawn: function Task_spawn(aTask) {
michael@0 139 return createAsyncFunction(aTask).call(undefined);
michael@0 140 },
michael@0 141
michael@0 142 /**
michael@0 143 * Create and return an 'async function' that starts a new task.
michael@0 144 *
michael@0 145 * This is similar to 'spawn' except that it doesn't immediately start
michael@0 146 * the task, it binds the task to the async function's 'this' object and
michael@0 147 * arguments, and it requires the task to be a function.
michael@0 148 *
michael@0 149 * It simplifies the common pattern of implementing a method via a task,
michael@0 150 * like this simple object with a 'greet' method that has a 'name' parameter
michael@0 151 * and spawns a task to send a greeting and return its reply:
michael@0 152 *
michael@0 153 * let greeter = {
michael@0 154 * message: "Hello, NAME!",
michael@0 155 * greet: function(name) {
michael@0 156 * return Task.spawn((function* () {
michael@0 157 * return yield sendGreeting(this.message.replace(/NAME/, name));
michael@0 158 * }).bind(this);
michael@0 159 * })
michael@0 160 * };
michael@0 161 *
michael@0 162 * With Task.async, the method can be declared succinctly:
michael@0 163 *
michael@0 164 * let greeter = {
michael@0 165 * message: "Hello, NAME!",
michael@0 166 * greet: Task.async(function* (name) {
michael@0 167 * return yield sendGreeting(this.message.replace(/NAME/, name));
michael@0 168 * })
michael@0 169 * };
michael@0 170 *
michael@0 171 * While maintaining identical semantics:
michael@0 172 *
michael@0 173 * greeter.greet("Mitchell").then((reply) => { ... }); // behaves the same
michael@0 174 *
michael@0 175 * @param aTask
michael@0 176 * The task function to start.
michael@0 177 *
michael@0 178 * @return A function that starts the task function and returns its promise.
michael@0 179 */
michael@0 180 async: function Task_async(aTask) {
michael@0 181 if (typeof(aTask) != "function") {
michael@0 182 throw new TypeError("aTask argument must be a function");
michael@0 183 }
michael@0 184
michael@0 185 return createAsyncFunction(aTask);
michael@0 186 },
michael@0 187
michael@0 188 /**
michael@0 189 * Constructs a special exception that, when thrown inside a legacy generator
michael@0 190 * function (non-star generator), allows the associated task to be resolved
michael@0 191 * with a specific value.
michael@0 192 *
michael@0 193 * Example: throw new Task.Result("Value");
michael@0 194 */
michael@0 195 Result: function Task_Result(aValue) {
michael@0 196 this.value = aValue;
michael@0 197 }
michael@0 198 };
michael@0 199
michael@0 200 function createAsyncFunction(aTask) {
michael@0 201 let asyncFunction = function () {
michael@0 202 let result = aTask;
michael@0 203 if (aTask && typeof(aTask) == "function") {
michael@0 204 if (aTask.isAsyncFunction) {
michael@0 205 throw new TypeError(
michael@0 206 "Cannot use an async function in place of a promise. " +
michael@0 207 "You should either invoke the async function first " +
michael@0 208 "or use 'Task.spawn' instead of 'Task.async' to start " +
michael@0 209 "the Task and return its promise.");
michael@0 210 }
michael@0 211
michael@0 212 try {
michael@0 213 // Let's call into the function ourselves.
michael@0 214 result = aTask.apply(this, arguments);
michael@0 215 } catch (ex if ex instanceof Task.Result) {
michael@0 216 return Promise.resolve(ex.value);
michael@0 217 } catch (ex) {
michael@0 218 return Promise.reject(ex);
michael@0 219 }
michael@0 220 }
michael@0 221
michael@0 222 if (isGenerator(result)) {
michael@0 223 // This is an iterator resulting from calling a generator function.
michael@0 224 return new TaskImpl(result).deferred.promise;
michael@0 225 }
michael@0 226
michael@0 227 // Just propagate the given value to the caller as a resolved promise.
michael@0 228 return Promise.resolve(result);
michael@0 229 };
michael@0 230
michael@0 231 asyncFunction.isAsyncFunction = true;
michael@0 232
michael@0 233 return asyncFunction;
michael@0 234 }
michael@0 235
michael@0 236 ////////////////////////////////////////////////////////////////////////////////
michael@0 237 //// TaskImpl
michael@0 238
michael@0 239 /**
michael@0 240 * Executes the specified iterator as a task, and gives access to the promise
michael@0 241 * that is fulfilled when the task terminates.
michael@0 242 */
michael@0 243 function TaskImpl(iterator) {
michael@0 244 this.deferred = Promise.defer();
michael@0 245 this._iterator = iterator;
michael@0 246 this._isStarGenerator = !("send" in iterator);
michael@0 247 this._run(true);
michael@0 248 }
michael@0 249
michael@0 250 TaskImpl.prototype = {
michael@0 251 /**
michael@0 252 * Includes the promise object where task completion callbacks are registered,
michael@0 253 * and methods to resolve or reject the promise at task completion.
michael@0 254 */
michael@0 255 deferred: null,
michael@0 256
michael@0 257 /**
michael@0 258 * The iterator returned by the generator function associated with this task.
michael@0 259 */
michael@0 260 _iterator: null,
michael@0 261
michael@0 262 /**
michael@0 263 * Whether this Task is using a star generator.
michael@0 264 */
michael@0 265 _isStarGenerator: false,
michael@0 266
michael@0 267 /**
michael@0 268 * Main execution routine, that calls into the generator function.
michael@0 269 *
michael@0 270 * @param aSendResolved
michael@0 271 * If true, indicates that we should continue into the generator
michael@0 272 * function regularly (if we were waiting on a promise, it was
michael@0 273 * resolved). If true, indicates that we should cause an exception to
michael@0 274 * be thrown into the generator function (if we were waiting on a
michael@0 275 * promise, it was rejected).
michael@0 276 * @param aSendValue
michael@0 277 * Resolution result or rejection exception, if any.
michael@0 278 */
michael@0 279 _run: function TaskImpl_run(aSendResolved, aSendValue) {
michael@0 280 if (this._isStarGenerator) {
michael@0 281 try {
michael@0 282 let result = aSendResolved ? this._iterator.next(aSendValue)
michael@0 283 : this._iterator.throw(aSendValue);
michael@0 284
michael@0 285 if (result.done) {
michael@0 286 // The generator function returned.
michael@0 287 this.deferred.resolve(result.value);
michael@0 288 } else {
michael@0 289 // The generator function yielded.
michael@0 290 this._handleResultValue(result.value);
michael@0 291 }
michael@0 292 } catch (ex) {
michael@0 293 // The generator function failed with an uncaught exception.
michael@0 294 this._handleException(ex);
michael@0 295 }
michael@0 296 } else {
michael@0 297 try {
michael@0 298 let yielded = aSendResolved ? this._iterator.send(aSendValue)
michael@0 299 : this._iterator.throw(aSendValue);
michael@0 300 this._handleResultValue(yielded);
michael@0 301 } catch (ex if ex instanceof Task.Result) {
michael@0 302 // The generator function threw the special exception that allows it to
michael@0 303 // return a specific value on resolution.
michael@0 304 this.deferred.resolve(ex.value);
michael@0 305 } catch (ex if ex instanceof StopIteration) {
michael@0 306 // The generator function terminated with no specific result.
michael@0 307 this.deferred.resolve();
michael@0 308 } catch (ex) {
michael@0 309 // The generator function failed with an uncaught exception.
michael@0 310 this._handleException(ex);
michael@0 311 }
michael@0 312 }
michael@0 313 },
michael@0 314
michael@0 315 /**
michael@0 316 * Handle a value yielded by a generator.
michael@0 317 *
michael@0 318 * @param aValue
michael@0 319 * The yielded value to handle.
michael@0 320 */
michael@0 321 _handleResultValue: function TaskImpl_handleResultValue(aValue) {
michael@0 322 // If our task yielded an iterator resulting from calling another
michael@0 323 // generator function, automatically spawn a task from it, effectively
michael@0 324 // turning it into a promise that is fulfilled on task completion.
michael@0 325 if (isGenerator(aValue)) {
michael@0 326 aValue = Task.spawn(aValue);
michael@0 327 }
michael@0 328
michael@0 329 if (aValue && typeof(aValue.then) == "function") {
michael@0 330 // We have a promise object now. When fulfilled, call again into this
michael@0 331 // function to continue the task, with either a resolution or rejection
michael@0 332 // condition.
michael@0 333 aValue.then(this._run.bind(this, true),
michael@0 334 this._run.bind(this, false));
michael@0 335 } else {
michael@0 336 // If our task yielded a value that is not a promise, just continue and
michael@0 337 // pass it directly as the result of the yield statement.
michael@0 338 this._run(true, aValue);
michael@0 339 }
michael@0 340 },
michael@0 341
michael@0 342 /**
michael@0 343 * Handle an uncaught exception thrown from a generator.
michael@0 344 *
michael@0 345 * @param aException
michael@0 346 * The uncaught exception to handle.
michael@0 347 */
michael@0 348 _handleException: function TaskImpl_handleException(aException) {
michael@0 349 if (aException && typeof aException == "object" && "name" in aException &&
michael@0 350 ERRORS_TO_REPORT.indexOf(aException.name) != -1) {
michael@0 351
michael@0 352 // We suspect that the exception is a programmer error, so we now
michael@0 353 // display it using dump(). Note that we do not use Cu.reportError as
michael@0 354 // we assume that this is a programming error, so we do not want end
michael@0 355 // users to see it. Also, if the programmer handles errors correctly,
michael@0 356 // they will either treat the error or log them somewhere.
michael@0 357
michael@0 358 let stack = ("stack" in aException) ? aException.stack : "not available";
michael@0 359 dump("*************************\n");
michael@0 360 dump("A coding exception was thrown and uncaught in a Task.\n\n");
michael@0 361 dump("Full message: " + aException + "\n");
michael@0 362 dump("Full stack: " + stack + "\n");
michael@0 363 dump("*************************\n");
michael@0 364 }
michael@0 365
michael@0 366 this.deferred.reject(aException);
michael@0 367 }
michael@0 368 };

mercurial