promall
Version:
Make creating and handling promises easy
95 lines (87 loc) • 2.25 kB
JavaScript
const executeFunction = function (f, ...params){
try{
if(f instanceof Promise){
return f;
} else if(typeof f === 'function') {
var res = f(...params);
if(res instanceof Promise){
return res;
} else {
return new Promise((resolve, reject) => {
try{
resolve(res);
} catch (error) {
reject(error);
}
});
}
} else {
return new Promise((resolve, reject) => {
try{
resolve(f);
} catch (error) {
reject(error);
}
});
}
} catch (error) {
if(exportFunction._doNotWrapErrors){
console.error(error);
throw error;
} else {
return new Promise((resolve, reject) => {
reject(error);
});
}
}
}
const awaitFunction = async function (f, ...params) {
return await executeFunction(f, ...params);
}
const exportFunction = executeFunction;
exportFunction._doNotWrapErrors = false;
exportFunction.doNotWrapErrors = () => { exportFunction._doNotWrapErrors = true; };
exportFunction.await = awaitFunction;
exportFunction.promise = executeFunction;
exportFunction.execute = executeFunction;
exportFunction.wrapErrors = () => { exportFunction._doNotWrapErrors = false; };
exportFunction.wrap = (f) => {
return function(...params) {
return executeFunction(f, ...params);
};
}
exportFunction.executeChain = function(chain, param){
if(chain){
return asynIter(chain, 0, param);
} else {
throw new Error('No promise function chain.');
}
}
async function asynIter(list, index, input){
if(list && index < list.length){
var result = await list[index](input);
if(result === undefined){
result = input;
}
if(index + 1 === list.length){
return result;
} else {
return asynIter(list, index + 1, result);
}
} else {
return input;
}
}
exportFunction.chain = exportFunction.executeChain;
exportFunction.all = function(...promises){
if(promises){
if(!Array.isArray(promises)){
promises = [promises];
}
return Promise.all(promises);
} else {
throw new Error('No input given, cannot create Promise.all().');
}
}
module.exports = executeFunction;