I'm working in an ES5 environment using jQuery. I have some code as follows:
var saveGame = function (gameState, saveStars) {
var deferred = $.Deferred();
var starsSaved = saveStars ? false : true;
model.game().saved(starsSaved);
model.driveAccessInProgress(true);
GW.manifest.saveGame(gameState).then(function () {
model.driveAccessInProgress(false);
deferred.resolve();
});
return deferred; // or deferred.promise()?
};
saveGame().then(/* more stuff */);
In this instance, whether I return deferred.promise() or just deferred the .then works as expected. Given this, I guess I'm a little unclear on what a promise is, and was wondering what the difference is between these two returns and when might it matter?
You want to return deferred.promise() so that the calling code can't call resolve or reject or other Deferred-specific methods. That's not something the caller should have access to. It should only be able to consume the promise, not affect its state. You can read the documentation as well .