0

Let's suppose we want to connect to our DB (whatever it is) through our NodeJS application, and that the code is as it follows:

let db = new Db()
let connection = db.connect()
db.findUserById('userID')

If we don't -somehow (for example, with Promises or a function*)- wait the connection to be finished (line 2), the findUserById will make the program crash because the db connection is not already done.

Well, let's now consider this other very simple (hope not too awkward) example:

let x = 3
let y = 5
let z = x * y * x * y * x * y // Just to simulate a time consuming operation
console.log(z) 

In this second example, why the fourth line waits until the z variable has a value assigned and doesn't happen the same in the first example? Or, in other words: how can I know when a JS function is asynchronous?

ljedrz
  • 20,316
  • 4
  • 69
  • 97
Franzech Domâs
  • 249
  • 2
  • 7
  • thats where callback function comes into action. – Rafi Ud Daula Refat Aug 28 '16 at 14:56
  • 2
    When the documentation says that it is asynchronous and/or when it accepts some kind of callback or anything similar. – Xaver Kapeller Aug 28 '16 at 14:57
  • 2
    @qxz, JavaScript array methods take callbacks, yet they're not asynchronous. – Rick Hitchcock Aug 28 '16 at 15:01
  • @qxz exceptions are things like `.forEach()`, `.map()` etc. – Pointy Aug 28 '16 at 15:01
  • 1
    just watch this: https://www.youtube.com/watch?v=8aGhZQkoFbQ – Gatsbill Aug 28 '16 at 15:06
  • FWIW, this is not a javascript-only thing. C, C#, Java, C++ (ever written a GUI app?), Python etc all can also do asynchronous things and have been for years. Javascript just happens to be one of the first popular language to **force** programmers to write programs in asynchronous style. But in other languages, if you want to write a GUI program or write a fast networking server you'll write asynchronous code too. – slebetman Aug 28 '16 at 15:08
  • @Pointy Right, sorry, forgot about those – qxz Aug 28 '16 at 15:09

0 Answers0