Last active
October 20, 2016 20:16
-
-
Save jthoms1/2350f0d46923a1b7831a21805174e5fa to your computer and use it in GitHub Desktop.
Create a promise from a node async function.
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
export interface Promisify { | |
<T>(func: (callback: (err: any, result: T) => void) => void): () => Promise<T>; | |
<T, A1>(func: (arg1: A1, callback: (err: any, result: T) => void) => void): (arg1: A1) => Promise<T>; | |
<T, A1, A2>(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void): (arg1: A1, arg2: A2) => Promise<T>; | |
<T, A1, A2, A3>(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void): (arg1: A1, arg2: A2, arg3: A3) => Promise<T>; | |
<T, A1, A2, A3, A4>(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise<T>; | |
<T, A1, A2, A3, A4, A5>(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise<T>; | |
} | |
/** | |
* @example: const rReadFile = promisify<Buffer, string>(fs.readFile); | |
* | |
*/ | |
export const promisify: Promisify = function(func: any) { | |
return (...args: any[]) => { | |
return new Promise((resolve, reject) => { | |
func(...args, (err: any, response: any) => { | |
if (err) { | |
return reject(err); | |
} | |
resolve(response); | |
}); | |
}); | |
}; | |
}; |
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 * as fs from 'fs'; | |
import promisify from './promisify'; | |
const filePath = '/things/stuff'; | |
const readFilePromised = promisify<Buffer, string>(fs.readFile); | |
(async function stuff () { | |
let fileContents = await readFilePromised(filePath); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment