class Scheduler { constructor ( max = 2 ) { this . maxNum = maxthis . runNum = 0 this . runlist = [ ] this . resolve = null this . complateNum = 0 } getRes ( list, max ) { this . list = listthis . maxNum = maxthis . result = [ ] return new Promise ( ( resolve, reject ) => { this . resolve = resolveif ( this . list. length === 0 ) { this . resolve ( this . result) return } this . runList ( ) } ) } runList ( ) { for ( let i = 0 ; i < this . list. length; i++ ) { this . runlist. push ( { index : i, cb : this . list[ i] } ) } this . run ( ) } run ( ) { while ( this . runNum < this . maxNum && this . runlist. length) { let itempro = this . runlist. shift ( ) let cb = itempro. cblet index = itempro. indexthis . runNum++ cb. then ( res => { this . result[ index] = res} ) . catch ( err => { this . result[ index] = err} ) . finally ( ( ) => { this . complateNum++ this . runNum-- console. log ( this . result) if ( this . complateNum == this . list. length) { this . resolve ( this . result) } else { this . run ( ) } } ) } } }
let proArr = [ ] for ( let i = 0 ; i < 100 ; i++ ) { let randomTime = Math. floor ( Math. random ( ) * 10 ) + 1 proArr. push ( new Promise ( ( resolve ) => { setTimeout ( ( ) => { resolve ( '-------' + i+ '--------' + randomTime) } , randomTime* 1000 ) } ) )
} let scheduler = new Scheduler ( )
scheduler. getRes ( proArr, 2 ) . then ( res => { console. log ( 'res' , res)
} )