tracer.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. define([
  2. "../_base/lang",
  3. "./Promise",
  4. "../Evented"
  5. ], function(lang, Promise, Evented){
  6. "use strict";
  7. // module:
  8. // dojo/promise/tracer
  9. /*=====
  10. return {
  11. // summary:
  12. // Trace promise fulfillment.
  13. // description:
  14. // Trace promise fulfillment. Calling `.trace()` or `.traceError()` on a
  15. // promise enables tracing. Will emit `resolved`, `rejected` or `progress`
  16. // events.
  17. on: function(type, listener){
  18. // summary:
  19. // Subscribe to traces.
  20. // description:
  21. // See `dojo/Evented#on()`.
  22. // type: String
  23. // `resolved`, `rejected`, or `progress`
  24. // listener: Function
  25. // The listener is passed the traced value and any arguments
  26. // that were used with the `.trace()` call.
  27. }
  28. };
  29. =====*/
  30. var evented = new Evented;
  31. var emit = evented.emit;
  32. evented.emit = null;
  33. // Emit events asynchronously since they should not change the promise state.
  34. function emitAsync(args){
  35. setTimeout(function(){
  36. emit.apply(evented, args);
  37. }, 0);
  38. }
  39. Promise.prototype.trace = function(){
  40. // summary:
  41. // Trace the promise.
  42. // description:
  43. // Tracing allows you to transparently log progress,
  44. // resolution and rejection of promises, without affecting the
  45. // promise itself. Any arguments passed to `trace()` are
  46. // emitted in trace events. See `dojo/promise/tracer` on how
  47. // to handle traces.
  48. // returns: dojo/promise/Promise
  49. // The promise instance `trace()` is called on.
  50. var args = lang._toArray(arguments);
  51. this.then(
  52. function(value){ emitAsync(["resolved", value].concat(args)); },
  53. function(error){ emitAsync(["rejected", error].concat(args)); },
  54. function(update){ emitAsync(["progress", update].concat(args)); }
  55. );
  56. return this;
  57. };
  58. Promise.prototype.traceRejected = function(){
  59. // summary:
  60. // Trace rejection of the promise.
  61. // description:
  62. // Tracing allows you to transparently log progress,
  63. // resolution and rejection of promises, without affecting the
  64. // promise itself. Any arguments passed to `trace()` are
  65. // emitted in trace events. See `dojo/promise/tracer` on how
  66. // to handle traces.
  67. // returns: dojo/promise/Promise
  68. // The promise instance `traceRejected()` is called on.
  69. var args = lang._toArray(arguments);
  70. this.otherwise(function(error){
  71. emitAsync(["rejected", error].concat(args));
  72. });
  73. return this;
  74. };
  75. return evented;
  76. });