简体   繁体   English

没有Q.resolve的诺言如何解决

[英]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. getpageinfos方法按预期运行。

However, if I take out Q.resolve... it still runs! 但是,如果我取出Q.resolve ...,它仍然可以运行! This is not expected. 这是不期望的。 How is getpageinfos getting executed if Q.resolve is not doing it? 如果Q.resolve不执行,getpageinfos如何执行? 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. Q.resolve所做的是获取一个值或一个承诺,并为其返回一个承诺。 This is useful because sometimes you want to wrap a value in a promise (for example Q.resolve(5) or Q(5) for short). 这很有用,因为有时您希望将值包装在Q.resolve(5)例如Q.resolve(5)Q(5)简称)。 It is also useful to convert promises from other libraries to Q promises. 将其他库中的承诺转换为Q承诺也很有用。

If you pass a Q promise into Q.resolve it doesn't do anything with it and just returns it. 如果将Q承诺传递给Q.resolve则它不会执行任何操作,只会返回它。 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. 请注意,promise是已经开始的操作 ,您不能仅听其完成或错误来“运行” promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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