forked from basicallydan/q-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait-for-multiple-promises.js
62 lines (55 loc) · 1.5 KB
/
wait-for-multiple-promises.js
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
var Q = require("q");
var oneA = function () {
var d = Q.defer();
var timeUntilResolve = Math.floor((Math.random()*2000)+1);
console.log('1A Starting');
setTimeout(function () {
console.log('1A Finished');
d.resolve('1ATime: ' + timeUntilResolve);
}, timeUntilResolve);
return d.promise;
};
var oneB = function () {
var d = Q.defer();
var timeUntilResolve = Math.floor((Math.random()*2000)+1);
console.log('1B Starting');
setTimeout(function () {
console.log('1B Finished');
d.resolve('1BTime: ' + timeUntilResolve);
}, timeUntilResolve);
return d.promise;
};
// This fuction throws an error which later on we show will be handled
var two = function (oneATime, oneBTime) {
var d = Q.defer();
console.log('OneA: ' + oneATime + ', OneB: ' + oneBTime);
console.log('2 Starting and Finishing, so 3A and 3B should start');
d.resolve();
//return d.promise;
};
var threeA = function () {
var d = Q.defer();
console.log('3A Starting');
setTimeout(function () {
console.log('3A Finished');
d.resolve();
}, Math.floor((Math.random()*2000)+1));
return d.promise;
};
var threeB = function () {
var d = Q.defer();
console.log('3B Starting');
setTimeout(function () {
console.log('3B Finished');
d.resolve();
}, Math.floor((Math.random()*5000)+1));
return d.promise;
};
var four = function () {
console.log('Four is now done');
};
Q.all([ oneA(), oneB() ])
.spread(two)
.then(function () { return Q.all([ threeA(), threeB() ]); })
.then(four)
.done();