1 | define([ |
---|
2 | "../_base/array", |
---|
3 | "../Deferred", |
---|
4 | "../when" |
---|
5 | ], function(array, Deferred, when){ |
---|
6 | "use strict"; |
---|
7 | |
---|
8 | // module: |
---|
9 | // dojo/promise/all |
---|
10 | |
---|
11 | var some = array.some; |
---|
12 | |
---|
13 | return function all(objectOrArray){ |
---|
14 | // summary: |
---|
15 | // Takes multiple promises and returns a new promise that is fulfilled |
---|
16 | // when all promises have been fulfilled. |
---|
17 | // description: |
---|
18 | // Takes multiple promises and returns a new promise that is fulfilled |
---|
19 | // when all promises have been fulfilled. If one of the promises is rejected, |
---|
20 | // the returned promise is also rejected. Canceling the returned promise will |
---|
21 | // *not* cancel any passed promises. |
---|
22 | // objectOrArray: Object|Array? |
---|
23 | // The promise will be fulfilled with a list of results if invoked with an |
---|
24 | // array, or an object of results when passed an object (using the same |
---|
25 | // keys). If passed neither an object or array it is resolved with an |
---|
26 | // undefined value. |
---|
27 | // returns: dojo/promise/Promise |
---|
28 | |
---|
29 | var object, array; |
---|
30 | if(objectOrArray instanceof Array){ |
---|
31 | array = objectOrArray; |
---|
32 | }else if(objectOrArray && typeof objectOrArray === "object"){ |
---|
33 | object = objectOrArray; |
---|
34 | } |
---|
35 | |
---|
36 | var results; |
---|
37 | var keyLookup = []; |
---|
38 | if(object){ |
---|
39 | array = []; |
---|
40 | for(var key in object){ |
---|
41 | if(Object.hasOwnProperty.call(object, key)){ |
---|
42 | keyLookup.push(key); |
---|
43 | array.push(object[key]); |
---|
44 | } |
---|
45 | } |
---|
46 | results = {}; |
---|
47 | }else if(array){ |
---|
48 | results = []; |
---|
49 | } |
---|
50 | |
---|
51 | if(!array || !array.length){ |
---|
52 | return new Deferred().resolve(results); |
---|
53 | } |
---|
54 | |
---|
55 | var deferred = new Deferred(); |
---|
56 | deferred.promise.always(function(){ |
---|
57 | results = keyLookup = null; |
---|
58 | }); |
---|
59 | var waiting = array.length; |
---|
60 | some(array, function(valueOrPromise, index){ |
---|
61 | if(!object){ |
---|
62 | keyLookup.push(index); |
---|
63 | } |
---|
64 | when(valueOrPromise, function(value){ |
---|
65 | if(!deferred.isFulfilled()){ |
---|
66 | results[keyLookup[index]] = value; |
---|
67 | if(--waiting === 0){ |
---|
68 | deferred.resolve(results); |
---|
69 | } |
---|
70 | } |
---|
71 | }, deferred.reject); |
---|
72 | return deferred.isFulfilled(); |
---|
73 | }); |
---|
74 | return deferred.promise; // dojo/promise/Promise |
---|
75 | }; |
---|
76 | }); |
---|