0

I'm struggling to get deferred to work how I would like it. Here is my test scenario:

function myFn(val) {

  var d = $.Deferred();

  console.log("starting: " + val);

  setTimeout(function() {
    console.log('timeover:' + val);
    d.resolve();
  }, 1000);

  console.log("ending: " + val);
  return d.promise();
}

test = myFn(1).done(myFn(2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The output is

starting: 1
ending: 1
starting: 2
ending: 2
timeover: 1
timeover: 2

where what I would like is:

starting: 1
timeover: 1
ending: 1
starting: 2
timeover: 2
ending: 2

Where have I misunderstood the deferred?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Hebbs
  • 17
  • 2
  • Simplest solution here would be `test = myFn(1).done(()=>{myFn(2)});` – Denys Séguret Mar 29 '17 at 07:41
  • `test = myFn(1).done(function() { myFn(2); });` See the linked question's answers for details. (That question's about `setTimeout`, but the problem is the same as your `done`. `.done(myFn(2))` **calls** `myFn(2)` and passes its return value into `done`, just like `foo(bar())` **calls** `bar` and passes its return value into `foo`.) – T.J. Crowder Mar 29 '17 at 07:41
  • Thanks - both worked perfectly. – Hebbs Mar 29 '17 at 08:03

0 Answers0