Skip to content

Instantly share code, notes, and snippets.

@futurist
Last active July 20, 2017 00:57
Show Gist options
  • Save futurist/69f4cc97f6f1e12327d190083348e663 to your computer and use it in GitHub Desktop.
Save futurist/69f4cc97f6f1e12327d190083348e663 to your computer and use it in GitHub Desktop.
Mithril promisify for 0.2.x using m.deferred
import m from 'mithril'
/**
* thatLooksLikeAPromiseToMe()
*
* Duck-types a promise.
*
* @param {object} o
* @return {bool} True if this resembles a promise
*/
function thatLooksLikeAPromiseToMe (o) {
return o && typeof o.then === 'function' && typeof o.catch === 'function'
}
/**
* promisify()
*
* Transforms callback-based function -- func(arg1, arg2 .. argN, callback) -- into
* an ES6-compatible Promise. Promisify provides a default callback of the form (error, result)
* and rejects when `error` is truthy. You can also supply settings object as the second argument.
*
* @param {function} original - The function to promisify
* @param {object} settings - Settings object
* @param {object} settings.thisArg - A `this` context to use. If not set, assume `settings` _is_ `thisArg`
* @param {bool} settings.multiArgs - Should multiple arguments be returned as an array?
* @return {function} A promisified version of `original`
*/
export default function promisify (original, settings) {
return function (...args) {
const returnMultipleArguments = settings && settings.multiArgs
let target
if (settings && settings.thisArg) {
target = settings.thisArg
} else if (settings) {
target = settings
}
var deferred = m.deferred()
var {resolve, reject} = deferred
// place callback
args.push(function callback (err, ...values) {
if (err) {
return reject(err)
}
if (false === !!returnMultipleArguments) {
return resolve(values[0])
}
resolve(values)
})
// Call the function
const response = original.apply(target, args)
if (thatLooksLikeAPromiseToMe(response)) {
resolve(response)
}
return deferred.promise
}
}
/*
promisify(
(arg, cb)=>setTimeout(cb, 500, null, arg)
)(123)
.then((arg)=>console.log('ok!', arg))
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment