0

I am just beginning to learn javascript, and have been provided the following answer to one of the js-assessment asynchronous testing problems.

var dfd = $.Deferred();
setTimeout(function() {
  dfd.resolve(value);
}, 10);
return dfd.promise();

I believe the above code is supposed to resolve the function after 10 seconds, but I've had trouble understanding the syntax. I am suspicious that it might be deprecated or an older style.

Does the $.Deferred() represent a promise because of the $? According to here it's just a random variable name (it can be easily be replaced with something like example_promise but I suspect might be wrong. Does a promise have to have a .resolved() function inside of it? And last, do I have to specify return dfd.promise() vs return dfd?

It might be much to ask, but basically I'd like a line-by-line breakdown of what's going on and why.

Community
  • 1
  • 1
Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
  • 2
    What you are looking at are jQuery's deferred objects (hence the `$`): http://learn.jquery.com/code-organization/deferreds/jquery-deferreds/ . They are similar to promises, but have a slightly different API. – Felix Kling Nov 26 '15 at 23:05
  • Awesome. I didn't even realize I was looking at jQuery, I thought I was learning Javascript. – Joseph Cho Nov 26 '15 at 23:07
  • And yet you tagged the question with jQuery ;) – Felix Kling Nov 26 '15 at 23:08
  • @JosephCho jQuery **is javascript**, it's just a library that makes writing javascript simpler – Wesley Smith Nov 26 '15 at 23:08
  • 2
    If you want to learn about native promises in JS, have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise . – Felix Kling Nov 26 '15 at 23:09
  • Thank you all! Clearly I'm just starting to learn. – Joseph Cho Nov 26 '15 at 23:09
  • @DelightedD0D: *" it's just a library that makes writing javascript simpler"* Lets say it makes working with the DOM and XMLHTTPRequest APIs easier. – Felix Kling Nov 26 '15 at 23:10
  • @FelixKling , that's a fair correction :) – Wesley Smith Nov 26 '15 at 23:10
  • Could someone comment so I can close this question out? I'm not sure how to do it otherwise. – Joseph Cho Nov 26 '15 at 23:12
  • Just click the checkmark next to your answer, but I think you have to wait 2 days to accept it when you answer your own question, Or you could just delete the question as it's not likely to help anyone in the future. I mean no offense by that, its just not likely to match any search someone does in the future looking for the same type of answer – Wesley Smith Nov 26 '15 at 23:12

1 Answers1

0

Turns out the syntax wasn't outdated or anything, I was just ignoring everything related to jQuery only to realize jQuery is part of javascript. For those just starting to learn, the links in the comments section are useful reading.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33