简体   繁体   中英

How is promise getting resolved without Q.resolve

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 example Q.resolve(5) or Q(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:

if (value instanceof Promise) {
    return value;
}

Note that a promise is an already started operation , you can't "run" a promise only listen to its completion or error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM