Skip to content

Instantly share code, notes, and snippets.

@beardedtim
Created July 13, 2018 15:47
Show Gist options
  • Select an option

  • Save beardedtim/357dde07ea62cea7bfdef6182cfe22ba to your computer and use it in GitHub Desktop.

Select an option

Save beardedtim/357dde07ea62cea7bfdef6182cfe22ba to your computer and use it in GitHub Desktop.
Promisfy and bind methods that reference `this`
const { promisify } = require('util') // node module
/**
* Creates Promise-returning functions from Callback-taking functions
* and binds the function to the created object via creation, mapped
* via methods
*
* @example
*
* const obj = { get, set, del }
* const promisified = promisifyMethods({
* creation: () => obj,
* methods: [
* 'get',
* // map obj.get to return.get
* 'set',
* ['remove', 'del'],
* // map obj.del to return.remove
* ]
* })
* // {
* // get: promisify(obj.get).bind(obj),
* // set: promisify(obj.set).bind(obj),
* // remove: promisify(obj.del).bind(obj)
* // }
*
* @param {PromisfyMethodsConfig} config - The configuration
* @return {Object}
*/
const promisifyMethods = (config) => {
const {
creation,
methods
} = config
const self = creation()
return methods.reduce((a, c) => {
// If method value is [string, string]
// map as [outgoing, incoming]
if (Array.isArray(c)) {
const [outgoing, incoming] = c
return Object.assign({}, a, {
[outgoing]: promisify(self[incoming]).bind(self)
})
}
// method is mapped one -> one
return Object.assign({}, a, {
[c]: promisify(self[c]).bind(self)
})
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment