How to convert callback to Promise in Javascript

Issue #416

1
2
3
4
5
6
7
8
9
10
11
12
13
// @flow

const toPromise = (f: (any) => void) => {
return new Promise<any>((resolve, reject) => {
try {
f((result) => {
resolve(result)
})
} catch (e) {
reject(e)
}
})
}
1
const videos = await toPromise(callback)

If a function accepts many parameters, we need to curry https://onmyway133.github.io/blog/Curry-in-Swift-and-Javascript/

1
2
3
4
5
6
7
8
9
10
function curry2(f) {
return (p1) => {
return (p2) => {
return f(p1, p2)
}
}
}

const callback = curry2(aFunctionThatAcceptsOptionsAndCallback)(options)
const items = await toPromise(callback)

Comments