Skip to content

Promise api #58

@newlix

Description

@newlix

Hi,
I found the promise api support is in the v1.0 proposal. I am using Koa , so the promise api is quite important for me. I try to promisify the dal.query and keep it backward compatible.

I turned this

query: function query($query, callback){
    var this_ = this, caller = arguments.callee.caller.name;

    callback = callback || utils.noop;

    if ( this.isSyncing && !$query.ignoreSync ){
      return this.syncQueue.push( function(){
        this_.query( $query, callback );
      });
    }

    this.runBeforeFilters( caller, $query, function( error ){
      if ( error ) return callback( error );

      var query = mosql.sql( $query );

      return this_.raw( query.toString(), query.values, function( error, result ){
        if ( error ) return callback( error );

        if ( validReturningQueryTypes.indexOf( $query.type ) > -1 || $query.returning ){
          return this_.runAfterFilters( caller, result.rows, $query, callback );
        }

        callback();
      });
    });
  }

into this

query: function query($query, callback){
    function _query($query,caller, callback){
      var this_ = this;

      if ( this.isSyncing && !$query.ignoreSync ){
        return this.syncQueue.push( function(){
          this_.query( $query, callback );
        });
      }

      this.runBeforeFilters( caller, $query, function( error ){
        if ( error ) return callback( error );

        var query = mosql.sql( $query );

        return this_.raw( query.toString(), query.values, function( error, result ){
          if ( error ) return callback( error );

          if ( validReturningQueryTypes.indexOf( $query.type ) > -1 || $query.returning ){
            return this_.runAfterFilters( caller, result.rows, $query, callback );
          }

          callback();
        });
      });
    }
    var this_ = this;
    var caller = arguments.callee.caller.name;
    return callback ? _query.call(this,$query,caller,callback) : new Promise(function(resolve,reject){
      _query.call(this_,$query,caller,function(error,result){
        if (error) reject(error);
        else resolve(result);
      });
    });
  }

And the other functions which return this.query($query,callback) inherently return promise now and are backward compatible. Some functions like findOne and raw need a little more works, but I think it won't be too hard.

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions