Skip to content

Instantly share code, notes, and snippets.

@akira345
Created March 3, 2020 11:15
Show Gist options
  • Save akira345/6f04855e45502d4e228ec6e9d267a955 to your computer and use it in GitHub Desktop.
Save akira345/6f04855e45502d4e228ec6e9d267a955 to your computer and use it in GitHub Desktop.
nodeJS Promise.All挙動確認
'use strict';
/**
* 指定した秒数ウエイトします。
* @param {number} waitSec 秒数(ms)
*/
const _sleep = ( waitSec ) => {
return new Promise( function ( resolve ) {
setTimeout( function () { resolve(); }, waitSec );
} );
};
const _errorhandler = ( e, message ) => {
console.log( message );
console.log( e.message );
throw e;
};
const funcException = async ( val ) => {
await _sleep( val * 1000 );
try {
throw new Error( `エラー:${ val }` );
} catch ( e ) {
console.log( "えらー:" + val );
throw e;
}
};
/**
* const objs = [...];
* await objs.forEachAsync(async (item) => {
* ...
* await someAsyncFunction();
* ...
* });
*
* @param {function} callback function(val, idx, obj)
*/
if ( !Array.prototype.forEachAsync ) {
Array.prototype.forEachAsync = async function ( callback ) {
for ( let index = 0; index < this.length; index++ ) {
await callback( this[ index ], index, this );
}
};
}
const main = async () => {
try {
const dummyArray = [ 5, 2, 3 ];
try {
console.log( "Start" );
await Promise.all( dummyArray.map( async ( val ) => {
await funcException( val );
} ) );
/*
await dummyArray.forEachAsync( async ( val ) => {
await funcException( val );
} );
*/
} catch ( e ) {
_errorhandler( e, "エラー発生!!" );
}
console.log( "正常終了" );
} catch ( e ) {
console.log( "異常終了" );
}
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment