0

I have the following:

var module = {}
module.setDate = function() {
    var d = new Date();
    return d;
}

Say I now have:

function logDate(){
   var date = module.setDate();
   console.log(date)
   console.log('finished')
}

Is the setting of var date to the return value of module.setDate() synchronous or asynchronous? Could the console ever look like:

undefined
'finished'
OliverJ90
  • 1,291
  • 2
  • 21
  • 42
  • _"Could the console ever look like..."_ No, the code posted will always return synchronously. But I feel like perhaps there's more to this question than you're asking? – James Thorpe Jan 18 '16 at 13:52
  • The function call to `.setDate()` will be synchronous. – Pointy Jan 18 '16 at 13:54
  • Not really tbh, I'm just wanting to use a slightly more complicated version of date setting like the above and was wondering if I could end up with an undefined date in `logDate()`. Thats what I was wanting to know for sure, thanks @Pointy. – OliverJ90 Jan 18 '16 at 13:55

1 Answers1

0

I think you're confusing a function call with a constructor.

var d = new Date();

This will create a Date object immediately, that that's what your function is returning.

On the other hand, if your function were

var module = {}
module.setDate = function() {
    return function() {
        var d = new Date();
        return d;
    }
}

This would be asynchronous, but not parallelly executed. The execution of the function you return would wait until you call the function.

function logDate(){
   var date = module.setDate();
   console.log(date() /* <--- need these parens, now! */)
   console.log('finished')
}

In order to truly execute in parallel, which I think it what you are trying to ask by saying "asynchronous", then I'd suggest reading up on one of these links.

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56