File: /home/f/r/e/frenchy/www/french-american.org/current/node_modules/uglyfly-js/lib/get_promisify.js
/***********************************************************************
Copyright (c)
Saair Quaderi <saair.quaderi@gmail.com> (UglyflyJS)
***********************************************************************/
/*globals define, module, require */
((typeof define === "function") ? define :
function () { "use strict"; require('./nd').apply(module, arguments); })(
"get_promisify",
[
],
function () {
"use strict";
function get_promisify(Promise) {
if (typeof Promise !== 'function') {
throw new TypeError('Promise is not a function');
}
/* promisify(fn, [receiver]) - Convert a function that expects a callback into a function that returns a Promise
* fn: A node-style asynchronus function:
* A node-style asynchronus function is a function which accepts a regular/irregular node-style callback function as a final argument
* A node-style callback function is a function expects the first argument to be an error or a falsy value if there was no error
* A regular node-style callback function takes any potential success value as only the second argument and accepts no other arguments
* An irregular node-style callback function expects multiple success values (with the first success value as the second argument)
* *Note: if the callback receives multiple values (has more than a second argument passed in), it is treated as irregular and
* the success values will be resolved by the Promise in the form of an array
* [thisArg]: An optional argument that provides the thisArg to be used as the context when running the asynchronous function
*/
function promisify(fn, thisArg) {
var thisArgProvided = (arguments.length >= 2);
if (typeof fn !== 'function') {
throw new TypeError('A function must be provided for promisification');
}
function promisifiedAsyncFn() { //expects same args as fn would have accepted except without the final argument (the callback function)
var argsArr = Array.prototype.slice.call(arguments);
thisArg = thisArgProvided ? thisArg : this;
return new Promise(function (resolve, reject) { //call promise constructor with function that takes resolve and reject callbacks as inputs
argsArr.push(function (err, result) { //node-style callback that ends the node-style callback chain and instead calls resolve and reject callbacks
if (err) {
reject(err);
} else {
resolve((arguments.length > 2) ? Array.prototype.slice.call(arguments, 1) : result);
}
});
fn.apply(thisArg, argsArr);
});
}
return promisifiedAsyncFn;
}
return promisify;
}
return get_promisify;
}
);