Created
October 7, 2018 15:51
-
-
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.
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
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