0

I am wondering if I can use $.when with a jquery selector or action as a deferred, like:

$.when(newTemplate.appendTo("#container")).done(function(){
    var rand = Math.floor((Math.random()*1000)+1);
    console.log(rand);
});

appendTo might not be async but reads like it would be

Is this going to wait for the appendTo to finish?

If not, how can I return a deferred obj from, in this case appendTo, so I will know when it is ready?

Dan Davies Brackett
  • 9,811
  • 2
  • 32
  • 54
Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

1 Answers1

2

Synchronous code is always completed before the next line, so you can just

newTemplate.appendTo("#container");
var rand = Math.floor((Math.random()*1000)+1);
console.log(rand);

What you pass to $.when should be an object implementing the Promise interface and encapsulate some asynchronous activity. If the activity is synchronous you can still do it of course but that's complicating the code a lot for absolutely no benefit whatsoever.

Esailija
  • 138,174
  • 23
  • 272
  • 326