Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know this is wrong, but essentially I want to

  • connect to a db/orm via a promise
  • wait on that promise to fulfill and get the models (the return from the promise)
  • use the results for form a middleware generator function to place the models on the request

I suspect that this isn't the best approach, so essentially I have two questions:

  • Should I be rewriting my db/orm connect to a generator function (I have a feeling that is more inline with koa style)
  • Back to the original question (as I am sure I will not get a chance to rewrite all my business logic) - how do I wait on a promise to fulfill and to then return a generator function?

This is my poor attempt - which is not working, and honestly I didn't expect it to, but I wanted to start by writing code, to have something to work with to figure this out:

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())
like image 976
akaphenom Avatar asked Nov 22 '25 19:11

akaphenom


1 Answers

According to this, you can do the following:

var domainMiddlewareImpl = function() {
    return function *(){
        this.request.models = yield connectImpl();
    };
};
like image 171
Hugo Wood Avatar answered Nov 25 '25 11:11

Hugo Wood