Skip to content

Instantly share code, notes, and snippets.

@Blair2004
Created October 7, 2018 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Blair2004/51681bcf4521e23d8565581aca5d44ca to your computer and use it in GitHub Desktop.
Save Blair2004/51681bcf4521e23d8565581aca5d44ca to your computer and use it in GitHub Desktop.
This help you to run queable promises and stop the execution if one promise reject an error.
function queuePromises({ promises, param, index = 0, total = 0, results = [] }) {
// promisesArray, _item
if( total === 0 ) {
total = promises.length;
}
console.log( `index is ${index}` );
return new Promise( ( resolve, reject ) => {
if( promises[ index ] !== undefined ) {
promises[ index ]( param ).then( response => {
results.push( response );
queuePromises({
promises,
param,
index : index + 1,
results,
total
}).then( result => {
resolve( result );
}).catch( error => {
reject( error );
})
}).catch( error => {
reject( error );
})
} else {
resolve({
status: 'success',
message: 'promise queue successful',
results
})
}
});
}
const promises = [
( param ) => {
return new Promise( ( resolve, reject ) => {
console.log( 'has run first =>' + param );
resolve(true);
})
},
( param ) => {
return new Promise( ( resolve, reject ) => {
console.log( 'has run second' );
resolve(true);
})
},
( param ) => {
return new Promise( ( resolve, reject ) => {
console.log( 'has run thirhd which fails' );
reject(false);
})
},
( param ) => {
return new Promise( ( resolve, reject ) => {
console.log( 'This should not run' );
resolve(true);
})
},
]
queuePromises({ promises, param: 'hello' }).then( result => {
console.log( result );
}).catch( error => {
console.log( error );
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment