I seem to have an issue whereby the two concurrent queries cause promise return values to be inconsistent. For instance, take the following code:
var db = require("monk")("localhost/trumps");
var Games = db.get("games");
var Cards = db.get("cards");
var userPromise = Cards.findById("53bd19796adf5b842e7f2b4d");
var aiPromise = Cards.findById("53bd19796adf5b842e7f2b5a");
var userCard;
var aiCard;
userPromise.then(function(userCardDoc) {
userCard = userCardDoc;
return "First Promise Return"
}).chain(aiPromise).then(function(aiCardDoc) {
aiCard = aiCardDoc;
return "Second Promise"
}).onFulfill(function(){
console.log("both fulfilled ", userCard, aiCard);
});
results in the following output:
both fulfilled
{ _id: 53bd19796adf5b842e7f2b4d,
image: 'images/austria/cards/teams_austria__0014_nakustealth.jpg',
name: 'teams_austria__0014_nakustealth.jpg',
attributes:
[ { name: 'wingspan', value: 14, unit: 'meters' },
{ name: 'speed', value: 19, unit: 'km/s' },
{ name: 'weight', value: 74, unit: 'kgs' },
{ name: 'creativity', value: 0, unit: 'points' } ] }
First Promise Return
notice that the value of the argument passed into the second promise handler gets set to the return value of the first handler.
In contrast, when I set a timeout:
var db = require("monk")("localhost/trumps");
var Games = db.get("games");
var Cards = db.get("cards");
var userPromise = Cards.findById("53bd19796adf5b842e7f2b4d");
var aiPromise = Cards.findById("53bd19796adf5b842e7f2b5a");
setTimeout(function(){
var userCard;
var aiCard;
userPromise.then(function(userCardDoc) {
userCard = userCardDoc;
return "First Promise Return"
}).chain(aiPromise).then(function(aiCardDoc) {
aiCard = aiCardDoc;
return "Second Promise"
}).onFulfill(function(){
console.log("both fulfilled")
console.log(userCard);
console.log(aiCard);
});
}, 100);
I get the expected results:
both fulfilled
{ _id: 53bd19796adf5b842e7f2b4d,
image: 'images/austria/cards/teams_austria__0014_nakustealth.jpg',
name: 'teams_austria__0014_nakustealth.jpg'}
{ _id: 53bd19796adf5b842e7f2b5a,
image: 'images/austria/cards/teams_austria__0027_feuerlöscherairaction.jpg',
name: 'teams_austria__0027_feuerlöscherairaction.jpg' }
I have tested the similar code using different collections and the issue still remains. Also, the timeout needed to ensure consistent result seems to vary as well, meaning unless I use a reasonably high value, there is a chance of this occurring.
A work around for me at the moment is simply nesting the success callbacks, however this is resulting in some nasty looking code.