简体   繁体   中英

Function with return value of other function as variable, async or not?

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM