-
Notifications
You must be signed in to change notification settings - Fork 0
/
all_and_reduce.js
68 lines (60 loc) · 2.16 KB
/
all_and_reduce.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
63
64
65
66
67
68
/**
* Created by Philip A Senger on 6/08/15.
*/
"use strict";
var Promise = require("bluebird"),
randomString = require('random-string');
/**
* Returns a random integer between min (included) and max (excluded) Using Math.round() will give you a non-uniform distribution!
*
* @param min
* @param max
* @returns {*}
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// create an array of promises.
var promises = [];
// create a promise that will fire off in some random amount of time, and push it into the array.
promises.push(function () {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve( { id: 1, data : randomString( { length: 20 } ) } );
}, getRandomInt( 100, 300 ) );
})
}());
// create a promise that will fire off in some random amount of time, and push it into the array.
promises.push(function () {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve( { id: 2, data : randomString( { length: 20 } ) } );
}, getRandomInt( 100, 300 ) );
})
}());
// create a promise that will fire off in some random amount of time, and push it into the array.
promises.push(function () {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve( { id: 3, data : randomString( { length: 20 } ) } );
}, getRandomInt( 100, 300 ) );
})
}());
// create a promise that will fire off in some random amount of time, and push it into the array.
promises.push(function () {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve( { id: 4, data : randomString( { length: 20 } ) } );
}, getRandomInt( 100, 300 ) );
})
}());
var starterObject = { results: [] };
// Execute them all, and reduce the results, to one final value.
Promise.all( promises )
.reduce(function(total, item, index, arrayLength){
total.results.push( item.data );
return total;
}, starterObject )
.then(function( results ){
console.log('Final results', results);
});