I am still learning promises and have run across this that makes no sense to me:
I have the below viewmodel. Notice the section:
var getpageinfos...
and below that:
Q.resolve(getpageinfos)...
The getpageinfos method runs as expected.
However, if I take out Q.resolve... it still runs! This is not expected. How is getpageinfos getting executed if Q.resolve is not doing it? This makes no sense to me.
How is it getting executed?
define(['services/unitofwork', 'services/errorhandler', 'plugins/router'], function (unitofwork, errorhandler, router) {
var unitofwork = unitofwork.create();
var viewmodel = {
convertRouteToHash: router.convertRouteToHash,
pageInfo: ko.observable(),
activate: function () {
ga('send', 'pageview', { 'page': window.location.href, 'title': document.title });
},
attached: function () {
var self = this;
var getpageinfos = unitofwork.pageinfos.all()
.then(function (pageinfos) {
self.pageInfo(pageinfos[0]);
});
return Q.resolve(getpageinfos).fail(self.handleError);
},
};
errorhandler.includeIn(viewmodel);
return viewmodel;
});
What
Q.resolve
does is take a value or a promise and return a promise for it. This is useful because sometimes you want to wrap a value in a promise (for exampleQ.resolve(5)
orQ(5)
for short). It is also useful to convert promises from other libraries to Q promises.If you pass a Q promise into
Q.resolve
it doesn't do anything with it and just returns it. It does:Note that a promise is an already started operation, you can't "run" a promise only listen to its completion or error.