3

Say we have

var x =3; 
var y = 4;
var z = x*y;
console.log(z);

How do we know it won't print an undefined variable z?

  • If it is asynchronous, is there a function used to assign values to variables with a callback so we can be certain of their values when using them.
  • If it is synchronous, then when loading modules like
var express = require('express');

Wouldn't that be pretty slow when you load a few of them in one script?

  • 1
    Possible duplicate of [Are JavaScript functions asynchronous?](http://stackoverflow.com/questions/15141118/are-javascript-functions-asynchronous). This thread should clear up any questions you have. – Robert Moskal May 11 '16 at 01:30
  • So nodejs is just normal javascript? I thought the entire point was that it is executed asynchronously. That still doesn't answer my question of whether it is slow to load multiple requires in one script. – SirKaliKook May 11 '16 at 01:49
  • http://ruben.verborgh.org/blog/2012/08/13/javascript-module-loaders-necessary-evil/ – jack blank May 11 '16 at 01:58
  • when you load modules with require most of the time it is not over the network (The files are on the server) so it wont be a long time. You might be thinking about requesting over the network which has latency. – jack blank May 11 '16 at 02:06

1 Answers1

9

Is variable assignment synchronous in nodejs?

Yes, it is.

Actually, any sequence of statements is executed synchronously.

You may be getting confused with the following type of situation:

var x = LongRunningAsyncTask();
console.log(x);

Here, LongRunningAsyncTask cannot return its result, since it is not yet known. Therefore, x probably won't be what you want, which is why, assuming LongRunningAsyncTask is implemented in callback style, you need to write

LongRunningAsyncTask(function callback(x) {
  console.log(x);
});

or if LongRunningAsyncTask returns a promise, then

LongRunningAsyncTask() . then(x => console.log(x));

or using async functions:

async function foo() {
  var x = await LongRunningAsyncTask();
  console.log(x);
}