Last active
July 20, 2017 00:57
-
-
Save futurist/69f4cc97f6f1e12327d190083348e663 to your computer and use it in GitHub Desktop.
Mithril promisify for 0.2.x using m.deferred
This file contains hidden or 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 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