-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathpromiseObjectAll.js
47 lines (44 loc) · 1017 Bytes
/
promiseObjectAll.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
const isPromise = require('./isPromise')
/**
* @name promiseObjectAllExecutor
*
* @synopsis
* ```coffeescript [specscript]
* promiseObjectAllExecutor(resolve function) -> ()
* ```
*/
const promiseObjectAllExecutor = object => function executor(resolve) {
const result = {}
let numPromises = 0
for (const key in object) {
const value = object[key]
if (isPromise(value)) {
numPromises += 1
value.then((key => function (res) {
result[key] = res
numPromises -= 1
if (numPromises == 0) {
resolve(result)
}
})(key))
} else {
result[key] = value
}
}
if (numPromises == 0) {
resolve(result)
}
}
/**
* @name promiseObjectAll
*
* @synopsis
* ```coffeescript [specscript]
* promiseObjectAll(object<Promise|any>) -> Promise<object>
* ```
*
* @description
* Like `Promise.all` but for objects.
*/
const promiseObjectAll = object => new Promise(promiseObjectAllExecutor(object))
module.exports = promiseObjectAll