Last active
July 26, 2016 13:02
-
-
Save jesseschalken/6e629dd19ea5791595562241767c8e68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs = require('fs') | |
type NodeCallback<T> = (err:any, data:T) => void | |
/** | |
* Accepts a function accepting a Node.js style callback, and calls it, returning a Promise | |
*/ | |
const promisify = <T>(func:(cb:NodeCallback<T>) => void) => | |
new Promise<T>((resolve, reject) => { | |
func((err, data) => { | |
if (err) { | |
reject(err) | |
} else { | |
resolve(data) | |
} | |
}) | |
}) | |
const promisify0 = <T>(func:(cb:NodeCallback<T>) => void) => | |
() => promisify<T>(cb => func(cb)) | |
const promisify1 = <P1, T>(func:(p1:P1, cb:NodeCallback<T>) => void) => | |
(p1:P1) => promisify<T>(cb => func(p1, cb)) | |
const promisify2 = <P1, P2, T>(func:(p1:P1, p2:P2, cb:NodeCallback<T>) => void) => | |
(p1:P1, p2:P2) => promisify<T>(cb => func(p1, p2, cb)) | |
const promisify3 = <P1, P2, P3, T>(func:(p1:P1, p2:P2, p3:P3, cb:NodeCallback<T>) => void) => | |
(p1:P1, p2:P2, p3:P3) => promisify<T>(cb => func(p1, p2, p3, cb)) | |
const promisify4 = <P1, P2, P3, P4, T>(func:(p1:P1, p2:P2, p3:P3, p4:P4, cb:NodeCallback<T>) => void) => | |
(p1:P1, p2:P2, p3:P3, p4:P4) => promisify<T>(cb => func(p1, p2, p3, p4, cb)) | |
async function test1():Promise<void> { | |
let fd = await promisify<number>(cb => fs.open('foo.txt', 'w', 'mode', cb)) | |
// ... | |
await promisify<void>(cb => fs.close(fd, cb)) | |
} | |
async function test2():Promise<void> { | |
let fd = await promisify3(fs.open)('foo.txt', 'w', 'mode') | |
// ... | |
await promisify1(fs.close)(fd) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment