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?

4
  • 1
    Possible duplicate of Are JavaScript functions asynchronous?. This thread should clear up any questions you have. Commented May 11, 2016 at 1: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. Commented May 11, 2016 at 1:49
  • ruben.verborgh.org/blog/2012/08/13/… Commented May 11, 2016 at 1: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. Commented May 11, 2016 at 2:06

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.