Debian Codegraph @

extensions/Echo/modules/api/mw.echo.api.PromisePrioritizer.js

raw symbols SCIP
1 ( function () {
2 /**
3 * Promise prioritizer for API actions. The prioritizer takes
4 * a promise at a time, always prioritizing the latest promise and
5 * aborting and ignoring the others.
6 *
7 * This allows us to send multiple promises in quick successions but
8 * trust that we get back only the latest successful request.
9 *
10 * @class
11 *
12 * @constructor
13 */
14 mw.echo.api.PromisePrioritizer = function MwEchoApiPromisePrioritizer() {
15 this.deferred = $.Deferred();
16 this.promise = null;
17 };
18
19 /* Initialization */
20
21 OO.initClass( mw.echo.api.PromisePrioritizer );
22
23 /**
24 * Prioritize a promise
25 *
26 * @param {jQuery.Promise|Promise} promise Promise
27 * @return {jQuery.Promise} The main deferred object that resolves
28 * or rejects when the latest promise is resolved or rejected.
29 */
30 mw.echo.api.PromisePrioritizer.prototype.prioritize = function ( promise ) {
31 const previousPromise = this.promise;
32
33 promise
34 .then(
35 this.setSuccess.bind( this, promise ),
36 this.setFailure.bind( this, promise )
37 );
38 this.promise = promise;
39
40 if ( previousPromise && previousPromise.abort ) {
41 previousPromise.abort();
42 }
43
44 return this.deferred.promise();
45 };
46
47 /**
48 * Set success for the promise. Resolve the main deferred object only
49 * if we are dealing with the currently prioritized promise.
50 *
51 * @param {jQuery.Promise} promise The promise that resolved successfully.
52 * The main deferred object is resolved with the result of the
53 * latest prioritized promise.
54 */
55 mw.echo.api.PromisePrioritizer.prototype.setSuccess = function ( promise ) {
56 if ( this.promise === promise ) {
57 this.promise.done( ( ...args ) => {
58 this.deferred.resolve( ...args );
59
60 this.promise = null;
61 this.deferred = $.Deferred();
62 } );
63 }
64 };
65
66 /**
67 * Set failure for the promise. Reject the main deferred object only
68 * if we are dealing with the currently prioritized promise.
69 *
70 * @param {jQuery.Promise} promise The promise that failed.
71 * The main deferred object is rejected with the result of the
72 * latest prioritized promise
73 */
74 mw.echo.api.PromisePrioritizer.prototype.setFailure = function ( promise ) {
75 if ( this.promise === promise ) {
76 this.promise.fail( ( ...args ) => {
77 this.deferred.reject( ...args );
78
79 this.promise = null;
80 this.deferred = $.Deferred();
81 } );
82 }
83 };
84 }() );