Undermine2k
Undermine2k

Reputation: 1491

jquery defered returning data on when

Hi i'm trying to understand $.deffered. How do i return data once say a computation has been completed?

function cube(n)
{
//console.log(n);
return n = Math.pow(n, 3);
}

function compute(n){
    var d = $.Deferred();

    n = cube(n);
    //how do i return n upon completed computation?
    return d.promise(n);
}



$.when(compute(5))
    .done(function(data){
        console.log(data);
    });

http://jsfiddle.net/ysfk00bc/

Upvotes: 1

Views: 48

Answers (1)

guest271314
guest271314

Reputation: 1

js at Question not appear to return value to jQuery.Deferred() callback handler .done() . See deferred.resolve() .

jQuery.Deferred() methods resolve , reject return value resolved or reason rejected to jQuery deferred methods .done , .fail , .then , always .

Try passing n as argument to .resolve() method of jQuery.Deferred() within compute , e.g., d.resolve(n).

Would not need to wrap compute(5) within $.when() - which returns a jQuery promise - as compute would return a jQuery promise object to .done() at return d.promise() .

function cube(n) {
  return Math.pow(n, 3);
}

function compute(n) {
  var d = new $.Deferred();
  n = cube(n);
  // return jQuery promise `n`: `cube(n)`
  d.resolve(n);
  return d.promise();
}

compute(5)
.done(function(data) {
  console.log(data);
});

compute(2)
.done(function(data) {
  console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>


Alternatively utilizing $.when() within compute , return jQuery promise n: cube(n)

function cube(n) {
  return Math.pow(n, 3);
}

function compute(n) {
  n = cube(n);
  // return jQuery promise `n`: `cube(n)`
  return $.when(n);
}

compute(5)
.done(function(data) {
  console.log(data);
});

compute(2)
.done(function(data) {
  console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Upvotes: 1

Related Questions