Queue + Task

Queue + Task structure

by Konstantin Cryman

JavaScript

class Task {

    constructor( foo, api, priority ) {
        this.foo = foo;
        this.api = api;
        this.priority = priority;
        this.status = 'pending'; // pending, process, completed, aborted
        this.created = Date.now();
        this.proceed = null;
        this.finished = null;
    }

    abort(){
        this.status = 'aborted';
        this.api.abort( this );
    }

    complete(){
        this.status = 'completed';
        this.finished = Date.now();
        this.api.complete( this );
    }

    run( onReady, onError){
        this.status = 'process';
        this.proceed = Date.now();
        return new Promise( ( resolveTask, rejectTask ) => {

            new Promise( this.foo ).then( ( result ) => {


                resolveTask( result );
                onReady( this, result );
                this.complete();

            }, ( err ) => {

                rejectTask(err);
                onError( this, err );
                this.abort();

            }).catch( ( err ) => {

                rejectTask(err);
                onError( this, err );
                this.abort();

            } );

        } );
    }

}

class Queue {

    constructor( options = this.defaultOptions ) {

        this.options = options;

        for( const key in this.defaultOptions ){
            if( !( key in this.options ) ){
                this.options[ key ] = this.defaultOptions[ key ];
            }
        }

        this.processLimit = this.options.processLimit;
        this.timePerTaskLimit = this.options.timePerTaskLimit;
        this.pending = [];
        this.process = [];
        this.completed = [];
        this.aborted = [];
        console.clear();
    }

    get defaultOptions(){
        return {
            name: 'defaultQueue',
            processLimit: 8,
            timePerTaskLimit: 50000,
            onReady: ( task, result ) => {},
            onError: ( task, reason ) => {},
            onProgress: ( info ) => {}
        };
   ...