promy.js 22.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
/*
 * Promy: Promises library
 * Copyright (C) 2013  Nexedi SA
 *
 *   This library is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global setInterval, setTimeout, clearInterval, clearTimeout */

(function (dependencies, module) {
  "use strict";
  /*global define, exports, window */
  if (typeof define === 'function' && define.amd) {
    return define(dependencies, module);
  }
  if (typeof exports === 'object') {
    module(exports);
  }
  if (typeof window === 'object') {
    window.promy = {};
    module(window.promy);
  }
}(['exports'], function (exports) {
  "use strict";

  var UNRESOLVED = 0, RESOLVED = 1, REJECTED = 2, CANCELLED = 3;

  /**
   * thenItem(item, [onSucess], [onError], [onProgress]): any
   *
   * Execute one of the given callback when the item is fulfilled. If the item
   * is not a promise, then onSuccess is called with the item as first
   * parameter.
   *
   * @param  {Any} item A promise, deferred or a simple value
   * @param  {Function} [onSuccess] The callback to call on resolve
   * @param  {Function} [onError] The callback to call on reject
   * @param  {Function} [onProgress] The callback to call on notify
   */
  function thenItem(item, onSuccess, onError, onProgress) {
    if (typeof item === 'object' && item !== null) {
      if (typeof item.promise === 'object' && item.promise !== null &&
          typeof item.promise.then === 'function') {
        // item seams to be a Deferred
        return item.promise.then(
          onSuccess,
          onError,
          onProgress
        );
      }
      if (typeof item.then === 'function') {
        // item seams to be a Promise
        return item.then(
          onSuccess,
          onError,
          onProgress
        );
      }
    }
    return onSuccess(item);
  }

  /**
   * promiseResolve(promise, answers): any
   *
   * Resolve the promise with the given answers.
   *
   * @param  {Promise} promise The promise to resolve
   * @param  {Array} answers The arguments to give
   */
  function promiseResolve(promise, answers) {
    var array;
    if (promise._state === UNRESOLVED) {
      promise._state = RESOLVED;
      promise._answers = answers;
      array = promise._onResolve.slice();
      setTimeout(function () {
        var i;
        for (i = 0; i < array.length; i += 1) {
          try {
            array[i].apply(promise, promise._answers);
          } catch (ignore) {} // errors will never be retrieved by global
        }
      });
      // free the memory
      promise._onResolve = undefined;
      promise._onReject = undefined;
      promise._onProgress = undefined;
    }
  }

  /**
   * promiseReject(promise, answers): any
   *
   * Reject the promise with the given answers.
   *
   * @param  {Promise} promise The promise to reject
   * @param  {Array} answers The arguments to give
   */
  function promiseReject(promise, answers) {
    var array;
    if (promise._state === UNRESOLVED) {
      promise._state = REJECTED;
      promise._answers = answers;
      array = promise._onReject.slice();
      setTimeout(function () {
        var i;
        for (i = 0; i < array.length; i += 1) {
          try {
            array[i].apply(promise, promise._answers);
          } catch (ignore) {} // errors will never be retrieved by global
        }
      });
      // free the memory
      promise._onResolve = undefined;
      promise._onReject = undefined;
      promise._onProgress = undefined;
    }
  }

  /**
   * promiseNotify(promise, answers): any
   *
   * Notify the promise with the given answers.
   *
   * @param  {Promise} promise The promise to notify
   * @param  {Array} answers The arguments to give
   */
  function promiseNotify(promise, answers) {
    var i;
    if (promise._onProgress) {
      for (i = 0; i < promise._onProgress.length; i += 1) {
        try {
          promise._onProgress[i].apply(promise, answers);
        } catch (ignore) {} // errors will never be retrieved by global
      }
    }
  }

  /**
   * Promise(cancel)
   *
   * @class Promise
   * @constructor
   */
  function Promise(cancel) {
    this._onReject = [];
    this._onResolve = [];
    this._onProgress = [];
    this._state = UNRESOLVED;
    if (typeof cancel === 'function') {
      this.promise._cancel = cancel;
    }
  }

  ////////////////////////////////////////////////////////////
  // http://wiki.commonjs.org/wiki/Promises/A
  // then(fulfilledHandler, errorHandler, progressHandler)

  /**
   * then([onSuccess], [onError], [onProgress]): Promise
   *
   * Returns a new Promise with the return value of the `onSuccess` or `onError`
   * callback as first parameter. If the pervious promise is resolved, the
   * `onSuccess` callback is called. If rejected, the `onError` callback is
   * called. If notified, `onProgress` is called.
   *
   *     Deferred.when(1).
   *       then(function (one) { return one + 1; }).
   *       then(console.log); // shows 2
   *
   * @method then
   * @param  {Function} [onSuccess] The callback to call on resolve
   * @param  {Function} [onError] The callback to call on reject
   * @param  {Function} [onProgress] The callback to call on notify
   * @return {Promise} The new promise
   */
  Promise.prototype.then = function (onSuccess, onError, onProgress) {
    /*global Deferred*/
    var defer, next = new this.constructor(this._cancel), that = this;
    defer = new Deferred();
    defer.promise = next;
    switch (this._state) {
    case RESOLVED:
      if (typeof onSuccess === 'function') {
        setTimeout(function () {
          try {
            thenItem(
              onSuccess.apply(that, that._answers),
              defer.resolve.bind(defer),
              defer.reject.bind(defer)
            );
          } catch (e) {
            defer.reject(e);
          }
        });
      } else {
        setTimeout(function () {
          defer.resolve.apply(defer, that._answers);
        });
      }
      break;
    case REJECTED:
      if (typeof onError === 'function') {
        setTimeout(function () {
          var result;
          try {
            result = onError.apply(that, that._answers);
            if (result === undefined) {
              return defer.reject.apply(defer, that._answers);
            }
            thenItem(
              result,
              defer.reject.bind(defer),
              defer.reject.bind(defer)
            );
          } catch (e) {
            defer.reject(e);
          }
        });
      } else {
        setTimeout(function () {
          defer.reject.apply(defer, that._answers);
        });
      }
      break;
    case UNRESOLVED:
      if (typeof onSuccess === 'function') {
        this._onResolve.push(function () {
          try {
            thenItem(
              onSuccess.apply(that, arguments),
              defer.resolve.bind(defer),
              defer.reject.bind(defer),
              defer.notify.bind(defer)
            );
          } catch (e) {
            defer.reject(e);
          }
        });
      } else {
        this._onResolve.push(function () {
          defer.resolve.apply(defer, arguments);
        });
      }
      if (typeof onError === 'function') {
        this._onReject.push(function () {
          try {
            thenItem(
              onError.apply(that, that._answers),
              defer.reject.bind(defer),
              defer.reject.bind(defer)
            );
          } catch (e) {
            defer.reject(e);
          }
        });
      } else {
        this._onReject.push(function () {
          defer.reject.apply(defer, that._answers);
        });
      }
      if (typeof onProgress === 'function') {
        this._onProgress.push(function () {
          var result;
          try {
            result = onProgress.apply(that, arguments);
            if (result === undefined) {
              defer.notify.apply(defer, arguments);
            } else {
              defer.notify(result);
            }
          } catch (e) {
            defer.notify.apply(defer, arguments);
          }
        });
      } else {
        this._onProgress.push(function () {
          defer.notify.apply(defer, arguments);
        });
      }
      break;
    default:
      break;
    }
    return next;
  };

  // p.resolve() ?
  // p.reject() ?
  // p.notify() ?

  /**
   * p.cancel(): p
   *
   * Cancels the operation by calling promise._cancel().
   *
   * @method cancel
   * @return {Promise} this
   */
  Promise.prototype.cancel = function () {
    if (this._state === UNRESOLVED) {
      this._state = CANCELLED;
      if (typeof this._cancel === 'function') {
        this._cancel();
      }
      this._onResolve = undefined;
      this._onReject = undefined;
      this._onProgress = undefined;
    }
    return this;
  };

  /**
   * p.timeout(delay): p
   *
   * Reject the promise with an Error("Timeout") and cancel the operation.
   *
   * @method timeout
   * @param  {Number} delay The delay before rejection
   * @return {Promise} this
   */
  Promise.prototype.timeout = function (delay) {
    return exports.choose(this, exports.delay(delay).then(function () {
      throw new Error("Timeout (" + delay + ")");
    }));
  };

  ////////////////////////////////////////////////////////////
  // http://wiki.commonjs.org/wiki/Promises/A
  // get(propertyName)

  /**
   * get(property): Promise
   *
   * Get the property of the promise response as first parameter of the new
   * Promise.
   *
   *     Deferred.when({'a': 'b'}).get('a').then(console.log); // shows 'b'
   *
   * @method get
   * @param  {String} property The object property name
   * @return {Promise} The promise
   */
  Promise.prototype.get = function (property) {
    return this.then(function (dict) {
      return dict[property];
    });
  };

  ////////////////////////////////////////////////////////////
  // http://wiki.commonjs.org/wiki/Promises/A
  // call(functionName, arg1, arg2, ...)

  /**
   * call(function_name, *args): Promise
   *
   *     Deferred.when({'a': console.log}).call('a', 'b'); // shows 'b'
   *
   * @method call
   * @param  {String} function_name The function to call
   * @param  {Any} *[args] The function arguments
   * @return {Promise} A new promise
   */
  Promise.prototype.call = function (function_name) {
    var args = Array.prototype.slice.call(arguments, 1);
    return this.then(function (dict) {
      return dict[function_name].apply(dict, args);
    });
  };

  /**
   * put(property, value): Promise
   *
   * Put a property value from a promise response and return the registered
   * value as first parameter of the new Promise.
   *
   *     Deferred.when({'a': 'b'}).put('a', 'c').then(console.log); // shows 'c'
   *
   * @method put
   * @param  {String} property The object property name
   * @param  {String} value The value to put
   * @return {Promise} A new promise
   */
  Promise.prototype.put = function (property, value) {
    return this.then(function (dict) {
      dict[property] = value;
      return dict[property];
    });
  };

  /**
   * p.done(callback): p
   *
   * Call the callback on resolve.
   *
   *     Deferred.when(1).
   *       done(function (one) { return one + 1; }).
   *       done(console.log); // shows 1
   *
   * @method done
   * @param  {Function} callback The callback to call on resolve
   * @return {Promise} This promise
   */
  Promise.prototype.done = function (callback) {
    var that = this;
    if (typeof callback !== 'function') {
      return this;
    }
    switch (this._state) {
    case RESOLVED:
      setTimeout(function () {
        try {
          callback.apply(that, that._answers);
        } catch (ignore) {} // errors will never be retrieved by global
      });
      break;
    case UNRESOLVED:
      this._onResolve.push(callback);
      break;
    default:
      break;
    }
    return this;
  };

  /**
   * p.fail(callback): p
   *
   * Call the callback on reject.
   *
   *     promisedTypeError().
   *       fail(function (e) { name_error(); }).
   *       fail(console.log); // shows TypeError
   *
   * @method fail
   * @param  {Function} callback The callback to call on reject
   * @return {Promise} This promise
   */
  Promise.prototype.fail = function (callback) {
    var that = this;
    if (typeof callback !== 'function') {
      return this;
    }
    switch (this._state) {
    case REJECTED:
      setTimeout(function () {
        try {
          callback.apply(that, that._answers);
        } catch (ignore) {} // errors will never be retrieved by global
      });
      break;
    case UNRESOLVED:
      this._onReject.push(callback);
      break;
    default:
      break;
    }
    return this;
  };

  /**
   * p.progress(callback): p
   *
   * Call the callback on notify.
   *
   *     Promise.delay(100, 10).
   *       progress(function () { return null; }).
   *       progress(console.log); // does not show null
   *
   * @method progress
   * @param  {Function} callback The callback to call on notify
   * @return {Promise} This promise
   */
  Promise.prototype.progress = function (callback) {
    if (typeof callback !== 'function') {
      return this;
    }
    switch (this._state) {
    case UNRESOLVED:
      this._onProgress.push(callback);
      break;
    default:
      break;
    }
    return this;
  };

  /**
   * p.always(callback): p
   *
   * Call the callback on resolve or on reject.
   *
   *     sayHello().
   *       done(iAnswer).
   *       fail(iHeardNothing).
   *       always(iKeepWalkingAnyway);
   *
   * @method always
   * @param  {Function} callback The callback to call on resolve or on reject
   * @return {Promise} This promise
   */
  Promise.prototype.always = function (callback) {
    var that = this;
    if (typeof callback !== 'function') {
      return this;
    }
    switch (this._state) {
    case RESOLVED:
    case REJECTED:
      setTimeout(function () {
        try {
          callback.apply(that, that._answers);
        } catch (ignore) {} // errors will never be retrieved by global
      });
      break;
    case UNRESOLVED:
      that._onReject.push(callback);
      that._onResolve.push(callback);
      break;
    default:
      break;
    }
    return this;
  };

  exports.Promise = Promise;

  /**
   * Deferred(cancel)
   *
   * @class Deferred
   * @constructor
   */
  function Deferred(cancel) {
    this.promise = new Promise(cancel);
  }

  /**
   * resolve(*args): any
   *
   * Resolves the promise with the given arguments.
   *
   * @method resolve
   * @param  {Any} *[args] The arguments to give
   */
  Deferred.prototype.resolve = function () {
    return promiseResolve(this.promise, arguments);
  };

  /**
   * reject(*args): any
   *
   * Rejects the promise with the given arguments.
   *
   * @method reject
   * @param  {Any} *[args] The arguments to give
   */
  Deferred.prototype.reject = function () {
    return promiseReject(this.promise, arguments);
  };

  /**
   * notify(*args): any
   *
   * Notifies the promise with the given arguments.
   *
   * @method notify
   * @param  {Any} *[args] The arguments to give
   */
  Deferred.prototype.notify = function () {
    return promiseNotify(this.promise, arguments);
  };

  exports.Deferred = Deferred;

  //////////////////////////////////////////////////////////////////////
  // Inspired by Task.js

  /**
   * now(value): Promise
   *
   * Converts an ordinary value into a fulfilled promise.
   *
   * @param  {Any} value The value to use
   * @return {Promise} The resolved promise
   */
  exports.now = function (value) {
    var deferred = new Deferred();
    deferred.resolve(value);
    return deferred.promise;
  };

  /**
   * join(*promises): Promise
   *
   * Produces a promise that is resolved when all the given promises are
   * resolved. The resolved value is an array of each of the resolved values of
   * the given promises.
   *
   * If any of the promises is rejected, the joined promise is rejected with the
   * same error, and any remaining unfulfilled promises are cancelled.
   *
   * @param  {Promise} *[promises] The promises to join
   * @return {Promise} A new promise
   */
  exports.join = function () {
    var promises, results = [], i, count = 0, deferred;
    promises = Array.prototype.slice.call(arguments);
    function cancel() {
      var j;
      for (j = 0; j < promises.length; j += 1) {
        promises[j].cancel();
      }
    }
    deferred = new Deferred(cancel);
    function succeed(j) {
      return function (answer) {
        results[j] = answer;
        count += 1;
        if (count !== promises.length) {
          return;
        }
        deferred.resolve(results);
      };
    }
    function failed(answer) {
      cancel();
      deferred.reject(answer);
    }
    function notify(j) {
      return function (answer) {
        deferred.notify({
          "promise": this,
          "index": j,
          "answer": answer
        });
      };
    }
    for (i = 0; i < promises.length; i += 1) {
      promises[i].then(succeed(i), failed, notify(i));
    }
    return deferred.promise;
  };

  /**
   * choose(*promises): Promise
   *
   * Produces a promise that is fulfilled when any one of the given promises is
   * fulfilled. As soon as one of the promises is fulfilled, whether by being
   * resolved or rejected, all the other promises are cancelled.
   *
   * @param  {Promise} *[promises] The promises to use
   * @return {Promise} A new promise
   */
  exports.choose = function () {
    var promises, i, deferred;
    promises = Array.prototype.slice.call(arguments);
    function cancel() {
      var j;
      for (j = 0; j < promises.length; j += 1) {
        promises[j].cancel();
      }
    }
    deferred = new Deferred(cancel);
    function succeed(answer) {
      cancel();
      deferred.resolve(answer);
    }
    function failed(answer) {
      cancel();
      deferred.reject(answer);
    }
    function notify(j) {
      return function (answer) {
        deferred.notify({
          "promise": this,
          "index": j,
          "answer": answer
        });
      };
    }
    for (i = 0; i < promises.length; i += 1) {
      promises[i].then(succeed, failed, notify(i));
    }
    return deferred.promise;
  };

  /**
   * sleep(delay[, every]): Promise
   *
   * Resolve the promise after `timeout` milliseconds and notfies us every
   * `every` milliseconds.
   *
   *     Deferred.delay(50, 10).then(console.log, console.error, console.log);
   *     // // shows
   *     // 10 // from progress
   *     // 20 // from progress
   *     // 30 // from progress
   *     // 40 // from progress
   *     // 50 // from progress
   *     // 50 // from success
   *
   * @param  {Number} delay In milliseconds
   * @param  {Number} [every] In milliseconds
   * @return {Promise} A new promise
   */
  exports.sleep = function (delay, every) {
    var deferred, timeout, interval, now = 0;
    function cancel() {
      clearTimeout(timeout);
      clearInterval(interval);
    }
    deferred = new Deferred(cancel);
    if (typeof every === 'number' && isFinite(every)) {
      interval = setInterval(function () {
        now += every;
        deferred.notify(now);
      }, every);
    }
    timeout = setTimeout(function () {
      clearInterval(interval);
      deferred.notify(delay);
      deferred.resolve(delay);
    }, delay);
    return deferred.promise;
  };

  ////////////////////////////////////////////////////////////
  // http://wiki.commonjs.org/wiki/Promises/B
  // when(value, callback, errback_opt)

  /**
   * when(item, [onSuccess], [onError], [onProgress]): Promise
   *
   * Return an item as first parameter of the promise answer. If item is of
   * type Promise, the method will just return the promise. If item is of type
   * Deferred, the method will return the deferred promise.
   *
   *     Deferred.when('a').then(console.log); // shows 'a'
   *
   * @param  {Any} item The item to use
   * @param  {Function} [onSuccess] The callback called on success
   * @param  {Function} [onError] the callback called on error
   * @param  {Function} [onProgress] the callback called on progress
   * @return {Promise} The promise
   */
  exports.when = function (item, onSuccess, onError, onProgress) {
    if (typeof item === 'object' && item !== null) {
      if (typeof item.promise === 'object' && item.promise !== null &&
          typeof item.promise.then === 'function') {
        // item seams to be a Deferred
        return item.promise.then(onSuccess, onError, onProgress);
      }
      if (typeof item.then === 'function') {
        // item seams to be a Promise
        return item.then(onSuccess, onError, onProgress);
      }
    }
    // item is just a value, convert into fulfilled promise
    var deferred = new Deferred(), promise;
    if (typeof onSuccess === 'function') {
      promise = deferred.promise.then(onSuccess);
    } else {
      promise = deferred.promise;
    }
    deferred.resolve(item);
    return promise;
  };

  ////////////////////////////////////////////////////////////
  // http://wiki.commonjs.org/wiki/Promises/B
  // get(object, name)

  /**
   * get(dict, property): Promise
   *
   * Return the dict property as first parameter of the promise answer.
   *
   *     Deferred.get({'a': 'b'}, 'a').then(console.log); // shows 'b'
   *
   * @param  {Object} dict The object to use
   * @param  {String} property The object property name
   * @return {Promise} The promise
   */
  exports.get = function (dict, property) {
    var p = new Deferred();
    try {
      p.resolve(dict[property]);
    } catch (e) {
      p.reject(e);
    }
    return p;
  };

  ////////////////////////////////////////////////////////////
  // http://wiki.commonjs.org/wiki/Promises/B
  // put(object, name, value)

  /**
   * put(dict, property, value): Promise
   *
   * Set and return the dict property as first parameter of the promise answer.
   *
   *     Deferred.put({'a': 'b'}, 'a', 'c').then(console.log); // shows 'c'
   *
   * @param  {Object} dict The object to use
   * @param  {String} property The object property name
   * @param  {Any} value The value
   * @return {Promise} The promise
   */
  exports.put = function (dict, property, value) {
    var p = new Deferred();
    try {
      dict[property] = value;
      p.resolve(dict[property]);
    } catch (e) {
      p.reject(e);
    }
    return p;
  };

}));