Last active
November 18, 2021 10:57
-
-
Save dmitry-tuzenkov/dce5582bc654898ea0574071192b1759 to your computer and use it in GitHub Desktop.
Nodejs simple es6 'promisify' 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
/* eslint-disable indent */ | |
/** | |
* Create a promise wrapper for function(err, arg1, ...argN) | |
* @param {function} fn - Function that should be promisified | |
* @returns {function} - Promisified function fn wrapper | |
* @example <caption>Example usage of promisify.</caption> | |
* const asynFn = require(...) // asynFn((err, a, b) => { ... }) | |
* const pMyFn = promisify(asynFn) | |
* console.log('asynFn result', await pMyfn(1, 2)) | |
*/ | |
const promisify = | |
(fn) => | |
(...args) => { | |
return new Promise((resolve, reject) => { | |
fn(...args, (err, ...args2) => (err ? reject(err) : resolve(...args2))) | |
}) | |
} | |
module.exports = { promisify } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment