-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresultOf.js
90 lines (75 loc) · 1.96 KB
/
resultOf.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
79
80
81
82
83
84
85
86
87
88
89
90
// run:
// node resultOf.js
/**
* @typedef {Array} AsyncResult
* @property {String|null} 1 - error upon failure
* @property {*} 2 - result upon success
*
* @example
* // on success
* [null, { result: { of: { async: { operation: true } } } } ] // on success
* ['error message', undefined] // on failure
*/
/**
* Standardizes async / await return values and removes the need for try/catch.
* Inspired by error handling in elixir.
*
* @param {Promise} - promised func invocation
* @return {Promise.<AsyncResult>}
*
* @example
*
* async func() {
* let [err, res] = await resultOf(asyncFunction())
* }
*/
const resultOf = (promise) => {
return promise
.then(data => {
return [null, data]
}).catch(err => {
return [err, null] // null added for illustrative purposes
})
}
/**
* Waits a bit and fails via Promise.reject().
*
* @return {Promise}
*/
const expectFailAsync = () => {
return new Promise((resolve, reject) => {
setTimeout(
() => reject('expectFailAsync ran out of time'),
1000
)
})
}
// Old way
const usingTryCatch = async () => {
let res
try {
res = await expectFailAsync()
}
catch (err) {
console.error(`OLD usingTryCatch Error: ${err}`)
return
}
}
usingTryCatch()
// new way
const usingResultOf = async (...args) => {
let [err, res] = await resultOf(expectFailAsync(args))
console.log(`NEW usingResultOf: ${JSON.stringify([err, res])}`)
}
usingResultOf()
const usingThenCatch = async (...args) => {
const result = await expectFailAsync(args)
.then(res => console.log(`ALT usingThenCatch:${JSON.stringify({res})}`))
.catch(err => console.log(`ALT usingThenCatch: ${JSON.stringify({err})}`)) // unneeded since all results are [err, res]
}
usingThenCatch()
/* prints to console:
OLD usingTryCatch Error: expectFailAsync ran out of time
ALT usingThenCatch: {"err":"expectFailAsync ran out of time"}
NEW usingResultOf: ["expectFailAsync ran out of time",null]
*/