How do I wait for a promise to fill and then return a generator function?

I know this is wrong, but essentially I want

  • connect to db / orm via promise
  • wait for this promise to fulfill and get the models (return from the promise)
  • use the results to form an intermediate generator function to place models on demand

I suspect this is not the best approach, so I have two questions:

  • Should I rewrite my db / orm connection with a generator function (I have a feeling it looks more like koa style).
  • Back to the original question (since I'm sure I won't have the opportunity to rewrite all my business logic) - how can I wait for the promise to be fulfilled and then return the generator function?

This is my failed attempt that doesn't work and to be honest I didn't expect this, but I wanted to start by writing some code to be able to work with this:

var connectImpl = function() {
  var qPromise = q.nbind(object.method, object);
  return qPromise ; 
}

var domainMiddlewareImpl = function() {
    let connectPromise = connectImpl()
    return connectPromise.then(function(models){
        return function *(next){
            this.request.models = models ;
        }
    })
}

var app = koa()
app.use(domainMiddlewareImpl())

      

+3


source to share


2 answers


According to this , you can do the following:



var domainMiddlewareImpl = function() {
    return function *(){
        this.request.models = yield connectImpl();
    };
};

      

+2


source


Context sensitive answer based on information provided by Hugo (thanks):

 var connectImpl = function() {
     var qPromise = q.nbind(object.method, object);
     return qPromise ; 
 }


var domainMiddlewareImpl = function () {
    let models = null ;
    return function *(next) {
        if(models == null){
            //////////////////////////////////////////////////////
            // we only want one "connection", if that sets up a 
            //     pool so be it
            //////////////////////////////////////////////////////
            models = yield connectImpl() ;
        }
        this.request.models = models.collections;
        this.request.connections = models.connections;
        yield next
    };
};

      



In my example, connectImpl configures the domain models in the ORM (waterline for now), connects to the database (merged), and returns a promise for the ORM models and DB connections. I want this to happen once, and then, for each request through my Koa middleware, add objects to the request.

0


source







All Articles