开发者

jquery defer not waiting before calling .done

I'm using defer's .done to wait for a cookie to be loaded before the function finishes. When I try to run the code it finishes and returns undefined. It seems like .done is firing before the first code can finish.

function getCookie(cookieName){
    var value;
    var defer = new jQuery.Deferred();
    fetchCookie().done(
        function(){
            return value;
        }
    );
    function fetchCookie(){
        chrome.cookies.get(
            {
            'url':'https://addictedtogether.com/',
            'name':cookieName
            },
            function(data){
                console.log(data);
                value=data.value;
            }
        );
        return defer.promise();
    }
}

//usage
var user开发者_如何学Pythonname=getCookie('username');


Deferred objects won't let you avoid callbacks. You still would need to be doing something like this (assuming everything is implemented correctly):

getCookie('username').then(function(username){
    console.log(username);
});

It will just generate unneeded overhead. I would rather simply do:

function getCookie(cookieName, callback){
    chrome.cookies.get(
        {
            'url':'https://addictedtogether.com/',
            'name':cookieName
        },
        function(data){
            console.log(data);
            value=data.value;
            if(callback) {
                callback(value);
            }
        }
    );
}

//usage
getCookie('username', function(username){
    console.log(username);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜