Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.97k stars 3.84k forks source link

Promises not working properly #1872

Closed pedroassis closed 10 years ago

pedroassis commented 10 years ago

Hello guys, I have this code:

var userPromise = EntityManager.getUserModel().find().exec('find'); // Also tried without the param 'find'

userPromise.then(function(data){
    console.log(data) // prints all users
}).then(function(data){
    console.log("second: " + data) // prints second: undefined
});

The first then callback gets call with the data, but all other in the chain gets undefined.

Also I'm facing another issue with promises: http://stackoverflow.com/questions/21077930/mongoose-promise-never-resolved

I'm using: nodejs 0.10.5 mongo 2.2 mongoose 3.8.4

I don't know if I should post this here or in mpromises repo, but I think I saw in your source that you alter the promises behavior.

Thanks in advance.

pedroassis commented 10 years ago

Well, I think that's a mpromises issue, avoiding the use of chaining promises "solved" the problem:

userPromise.then(function(data){
    console.log(data) // prints all users
});
    userPromise.then(function(data){
    console.log("second: " + data) // prints second plus all users.
});
refack commented 10 years ago

What you are describing is the defined behaviour. Chained .then()s require that either the data or a promise for data be returned, i.e.

EntityManager.getUserModel().find().exec().then(function (data1) {
    console.log(data1)
    return data1; // << This is where this scope return the data
}).then(function (data2) {
    console.log("second: " + data2)
}).end(); // also if you know this is the end of the chain, you should declare that.
pedroassis commented 10 years ago

Yeah, I have researched a lot on Promises A+, and it's a little confusing

On http://promises-aplus.github.io/promises-spec/ it says that if either onFulfilled or onRejected returns a value x, that value should be provided to the next chained promise's onFulfill callback.

undefined is a value, a valid value for a promise, but the problem is that it isn't returned directly by onFulfill, should it be called a "returned value"?

Anyway, this is getting too deep and I happy to understand more about promises. Thanks.