@@ -42,8 +42,23 @@ module.exports = class TimeQueue extends EventEmitter {
4242 *
4343 * @param {Object } ...args
4444 * @param {Function(!Error, ...) } callback
45+ * @return {Promise? }
4546 */
4647 push ( ...args ) {
48+ // Returns a promise if no `callback` is given.
49+ if ( args . length < this . worker . length ) {
50+ return new Promise ( ( resolve , reject ) => {
51+ // Add any missing arguments.
52+ while ( args . length < this . worker . length - 1 ) {
53+ args . push ( undefined ) ;
54+ }
55+ this . push ( ...args , ( err , results ) => {
56+ if ( err ) return reject ( err ) ;
57+ resolve ( results ) ;
58+ } ) ;
59+ } ) ;
60+ }
61+
4762 if ( this . isFull ( ) ) {
4863 return ;
4964 }
@@ -78,7 +93,7 @@ module.exports = class TimeQueue extends EventEmitter {
7893 * @param {Array.<Object> } args
7994 */
8095 _process ( args ) {
81- const callback = args . splice ( this . worker . length - 1 , 1 ) [ 0 ] ;
96+ const callback = args . pop ( ) ;
8297 let finished = false ;
8398 let every = ~ ~ this . every ;
8499 let timedOut ;
@@ -104,7 +119,7 @@ module.exports = class TimeQueue extends EventEmitter {
104119 let timeout = ~ ~ this . timeout ;
105120 let tid ;
106121
107- const taskCallback = ( err , ... args ) => {
122+ const taskCallback = ( err , result ) => {
108123 // If this task has timed out, and the callback is called again
109124 // from the worker, ignore it.
110125 if ( ! taskTimedOut ) {
@@ -118,19 +133,9 @@ module.exports = class TimeQueue extends EventEmitter {
118133 throw Error ( 'Callback from worker should only be called once' ) ;
119134 }
120135 callbackCalled = true ;
121-
122136 this . finished ++ ;
123137 this . active -- ;
124-
125- if ( typeof callback === 'function' ) {
126- // If a callback was given with the task,
127- // call it when the task is finished.
128- callback ( err , ...args ) ;
129-
130- } else if ( err ) {
131- // Otherwise emit an `error` event if there was an error with the task.
132- this . emit ( 'error' , err ) ;
133- }
138+ callback ( err , result ) ;
134139
135140 finished = true ;
136141 if ( timedOut ) {
@@ -147,11 +152,6 @@ module.exports = class TimeQueue extends EventEmitter {
147152 } , timeout ) ;
148153 }
149154
150- // Add missing arguments.
151- while ( args . length < this . worker . length - 1 ) {
152- args . push ( undefined ) ;
153- }
154-
155155 // Add custom callback to args.
156156 const args2 = args . slice ( ) ;
157157 args2 . push ( taskCallback ) ;
0 commit comments