简体   繁体   English

done()是否也可以在int上工作?

[英]does done() work on ints as well?

I have this code in javascript (jquery) 我在javascript(jquery)中有此代码

function getTopLevelId(gender) {
            var catId = $.ajax({
            type: 'GET',
            url: '{url}'
            dataType: 'html'
        });

        return catId;   //Returns defered object    
    }

function getSelectedCategoryId() {
    return 7; //returns int based on value in an element
};


function mainFuncion(id) {
    if (parseInt(id) === 0) {
        catObj= getTopLevelId(gender);    //Returns defered object       
    }
    else {
        catId = getSelectedCategoryId(id);  //Returns int
        catObj = catId;
    }

    $.when(catObj).done(function(catId) {
            //Doing some stuff and want to use catId as a category id
    }
}

My question is about "Doing some stuff" in done(). 我的问题是关于done()中的“做一些事情”。 It SEEMS to me like done() is called and giving me correct category id even if catId is just an int, but is this always true? 在我看来 ,像有()被调用 ,并给了我正确的类ID即使catId仅仅是一个整数,但是这始终是真的吗? Or is there any other way that might be "safer" to achieve what I want in mainFunction? 还是有其他方法可能更“安全”地实现我在mainFunction中想要的?

Yes. 是。 If none of the params passed to $.when() are unresolved promise objects then the done handler is called immediately. 如果没有传递到PARAMS的$.when()是未解决的承诺对象则done处理程序立即调用。

If a single argument is passed to jQuery.when and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately. 如果将单个参数传递给jQuery.when并且它不是Deferred或Promise,它将被视为已解析的Deferred,并且将立即执行任何附加的doneCallbacks。 The doneCallbacks are passed the original argument. doneCallbacks传递给原始参数。 In this case any failCallbacks you might set are never called since the Deferred is never rejected. 在这种情况下,您可能设置的任何failCallbacks都不会被调用,因为Deferred不会被拒绝。

var a = 7;
$.when(a).done(function (x) {
    console.log('inside', x)
});
console.log('after')

Demo: Fiddle , Fiddle2 演示: FiddleFiddle2

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

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