promise-maker
Version:
Turn callback-based functions and methods into Promise-based methods for later use or immediate execution.
69 lines (63 loc) • 2.29 kB
JavaScript
module.exports = {
//Return a promise-based version of a callback-based async method.
create : function(func, resolves = false){
if(typeof resolves !== 'boolean' && typeof resolves !== 'number' && resolves != 'all'){
throw new Error('Invalid value submitted for \'resolves\' argument.')
}
return function(){
return new Promise((resolve, reject)=>{
var params = [...arguments, function(...args){
//check for error hooks
var error = false;
for(let arg of args){
if(arg instanceof Error){
error = arg;
break;
}
}
if(error){
reject(error)
}else{
switch(resolves){
case false:
resolve(arguments.length == 1 ? arguments[0] : arguments[1])
break;
case true:
resolve(true)
break;
case 'all':
resolve(args)
break;
default:
resolve(args[resolve])
}
}
}]
func.apply(null, params)
})
}
},
/*Execute a callback-based async function as a promise and have the return value
resolved as a promise output passed to the .then() method.
Uses same approach for resolving final value as 'create'.
While 'create' returns a function that can be stored and used repeatedly;
'complete' executes the async method as a promise once and is not reusable.
'complete' also limits the callback arguments you can resolve to the first
or second argument, following the standard Node.js API pattern of (err, data)
as the assumed callback structure. This means if arguments.length > 1, the second
argument value will be resolved, while arguments.length == 1 will resolve the lone
argument value, even if it is a null error value, as is the case in some Node.js
callbacks.*/
complete : function(func, ...params){
return new Promise((resolve, reject)=>{
params.push(function(){
if(arguments[0] instanceof Error){
reject(arguments[0])
}else{
resolve(arguments.length == 1 ? arguments[0] : arguments[1])
}
})
func.apply(null, params)
})
}
}