/
promise_utils.js
78 lines (73 loc) · 1.74 KB
/
promise_utils.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
69
70
71
72
73
74
75
76
77
78
/**
* utility functions for working with Promises
*/
const Promise = require("bluebird")
Promise.onPossiblyUnhandledRejection(function(e, promise) {
throw e
})
/**
* checks if `p` is a promise, returning true or false
*
* @param {*} p - argument to check if promise
* @return {Boolean}
*/
const is_promise = (p) => {
if (p && p.then && typeof p.then === "function") {
return true
}
return false
}
/**
* calls a function with `args` (array of arguments)
* wraps the result of `fn` as a Promise
*
* if it's not a function, it returns the value wrapped
* as a Promise
*
* @param {function} fn - the function as defined by the user
* @param {*[]} args - an array of arguments to `fn`
* @return {Promise}
*/
const callp = (fn, args) => {
if (typeof fn === "function") {
return new Promise((resolve, reject) => {
resolve(fn.apply(undefined, args))
})
}
return Promise.resolve(fn)
}
const response = require("../http/response")
/**
* Resolve a Promise of a Promise (as it pertains to a response
* map)
*
* For adding an extra step to resolve Promises that are
* a response map, where the body itself is a promise
*
* This avoids the promise of a promise issue when dealing
* with response maps
*
* @param {Promise} p - a promise
* @return {Promise}
*/
const resolve_response = (p) => {
return p.then((result) => {
// if it is a response map, resolve the body
if (response.is_response(result)
&& is_promise(result.body)) {
return new Promise((resolve, reject) => {
result.body.then((body) => {
result.body = body
resolve(result)
})
})
}
// otherwise just return
return result
})
}
module.exports = {
callp,
resolve_response,
is_promise
}