]>
Commit | Line | Data |
---|---|---|
f0cfe83e AD |
1 | define("dojo/when", [ |
2 | "./Deferred", | |
3 | "./promise/Promise" | |
4 | ], function(Deferred, Promise){ | |
5 | "use strict"; | |
6 | ||
7 | // module: | |
8 | // dojo/when | |
9 | ||
10 | return function when(valueOrPromise, callback, errback, progback){ | |
11 | // summary: | |
12 | // Transparently applies callbacks to values and/or promises. | |
13 | // description: | |
14 | // Accepts promises but also transparently handles non-promises. If no | |
15 | // callbacks are provided returns a promise, regardless of the initial | |
16 | // value. Foreign promises are converted. | |
17 | // | |
18 | // If callbacks are provided and the initial value is not a promise, | |
19 | // the callback is executed immediately with no error handling. Returns | |
20 | // a promise if the initial value is a promise, or the result of the | |
21 | // callback otherwise. | |
22 | // valueOrPromise: | |
23 | // Either a regular value or an object with a `then()` method that | |
24 | // follows the Promises/A specification. | |
25 | // callback: Function? | |
26 | // Callback to be invoked when the promise is resolved, or a non-promise | |
27 | // is received. | |
28 | // errback: Function? | |
29 | // Callback to be invoked when the promise is rejected. | |
30 | // progback: Function? | |
31 | // Callback to be invoked when the promise emits a progress update. | |
32 | // returns: dojo/promise/Promise | |
33 | // Promise, or if a callback is provided, the result of the callback. | |
34 | ||
35 | var receivedPromise = valueOrPromise && typeof valueOrPromise.then === "function"; | |
36 | var nativePromise = receivedPromise && valueOrPromise instanceof Promise; | |
37 | ||
38 | if(!receivedPromise){ | |
39 | if(callback){ | |
40 | return callback(valueOrPromise); | |
41 | }else{ | |
42 | return new Deferred().resolve(valueOrPromise); | |
43 | } | |
44 | }else if(!nativePromise){ | |
45 | var deferred = new Deferred(valueOrPromise.cancel); | |
46 | valueOrPromise.then(deferred.resolve, deferred.reject, deferred.progress); | |
47 | valueOrPromise = deferred.promise; | |
48 | } | |
49 | ||
50 | if(callback || errback || progback){ | |
51 | return valueOrPromise.then(callback, errback, progback); | |
52 | } | |
53 | return valueOrPromise; | |
54 | }; | |
55 | }); |