0

I have promise as following code. After I have resolved promise with parameter, I want to get parameter in done() method.

function splitAndSetTebiskopUrl(tebiskopUrl){
    splits = tebiskopUrl.split("\u0007");
    tebiskopUrl = splits[0];
    var defer = $.Deferred();
    if(splits[1]){
        var cookieValue = splits[1];

        return $.ajax({
            type:'POST', 
            url:'xxxxxxxxxxxx', 
            data:{'cookieValue':cookieValue},

        }).then(function(data){
            if(data && data.cookieValue){
                defer.resolve(tebiskopUrl);

            }else{
                defer.reject("cookie value doesn't exist");
            }
        },
          function(){
            defer.reject("tebiskopCookieSet request error");
        });

    }else{
        defer.resolve(tebiskopUrl);
    }

    return defer.promise(); 
}

The parameter is not passed to done() method. Unfortunetly I get it as undefined. I have looked a lot of example. But I can't find the problem.

splitAndSetTebiskopUrl(url).done(function(parameter){
                //parameter is undefined
             });
yunus kula
  • 859
  • 3
  • 10
  • 31
  • Avoid the [deferred antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 22 '18 at 07:28
  • @Bergi What can I use other. Can you give example ? . I have two condition. In first condition , we have to wait ajax result and In second condition , without ajax I have to return given parameter. – yunus kula Jan 22 '18 at 07:35

1 Answers1

1

In the if block, you are returning the promise from the chained then call - the promise of the defer that you resolve will not be returned here. You could just omit that return keyword and the code would work, but really you should avoid the deferred antipattern and indeed simply return the promise from the chain:

function splitAndSetTebiskopUrl(tebiskopUrl){
    var splits = tebiskopUrl.split("\u0007");
    tebiskopUrl = splits[0];
    if (splits[1]) {
        return $.ajax({
            type:'POST', 
            url:'xxxxxxxxxxxx', 
            data:{'cookieValue': split[1]},
        }).then(function(data){
            if (data && data.cookieValue) {
                return tebiskopUrl;
            } else {
                throw new Error("cookie value doesn't exist");
            }
        }, function(err) {
            throw new Error("tebiskopCookieSet request error");
        });
    } else {
        return $.when(tebiskopUrl);
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375