0

I have this source code:

UserSchema.post('save', function (next) {
    doSomethingAsync(function(){
        next()
    });
});

myFunc = function(user){
     Q.ninvoke(user, 'save').then(function(){
          doThisAtTheEnd()
     });
}

But then is called before "doSomethingAsync" calls is callback. How is it possible?! How can I call "then" after all the saving stuff is done?

Thanks very much

EDIT: the two functions are in different files, no way nor intention to use a global variable.

M4rk
  • 2,172
  • 5
  • 36
  • 70

1 Answers1

0

From the documentation for Q.ninvoke: https://github.com/kriskowal/q/wiki/API-Reference#qninvokeobject-methodname-args

Calls a Node.js-style method with the given variadic arguments, returning a promise that is fulfilled if the method calls back with a result, or rejected if it calls back with an error (or throws one synchronously)

And looking at mongoose schema.post('save'): http://mongoosejs.com/docs/middleware.html

post middleware are executed after the hooked method and all of its pre middleware have completed. post middleware do not directly receive flow control, e.g. no next or done callbacks are passed to it. post hooks are a way to register traditional event listeners for these methods.

Which means that there is no next for you to call in the doSomethingAsync. Probably something is internally calling back into the ninvoke.

How about deferers? You could generate a deferer and resolve it. i.e.:

var saveDeferer = Q.defer();

UserSchema.post('save', function (next) {
    doSomethingAsync(function(){
        saveDeferer.resolve();
    });
});

saveDeferer.promise.then( function() { doSomething(); } );

Update after the question edit:

It seems to me that you are trying to use schema.post('save', ... as an eventbus that carries flow variables around. I don't see any direct answer to your edit, other than either use a custom event bus, or do some refactoring so that you can pass the promise references around.

fmsf
  • 36,317
  • 49
  • 147
  • 195