0

I feel something does not fit in my picture, when I try to wrap my head around async-programming. Every JavaScript tutorial says something like:

Every time an expensive operation occurs, we pass a callback function that will be called once we can continue with the processing. We’re not waiting for that to finish before going on with the rest of the program.

How I see it, when we execute some command, we need the result of this code for next command. So, how could async call not to block execution, when we need the result of the async call in rest of our program?

For example such simple code:

var a = 12;
var c = 0;

function sum( data ) {
  console.log( data.b + a );
  c = data.b + a // global c here
  console.log( 'and now we can continue with next command' );
}

verySlowAndExpensiveAsyncCall( a, sum ); 
console.log( 'can we execute this without waiting previous to finish?' );
console.log( c );

For my procedural mind I feel I can't execute any next command anyway, because I need the value of c to continue. So where is the non-blocking nature here?

My question is maybe not strictly Stack Overflow-questions, but it is fundametal to understand async-programming and I have read a lot of docs and somehow missed this important part: why and when (on which conditions) asynchronous code is non-blocking?

I expect either explanation or source of the explanation as answer.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
w.k
  • 8,218
  • 4
  • 32
  • 55
  • 1
    `because I need the value of c to continue` No, you don't. You can't wait for `c`, thats why you pass a callback. Your two `console.log` lines at the bottom will execute before `sum` is called. – tkausl Sep 18 '18 at 11:01
  • `verySlowAndExpensiveAsyncCall` will be processing something *in the background*, and when it's done it'll execute the `sum` callback you gave it. In the meantime, the rest of the code below `verySlowAndExpensiveAsyncCall(...)` will continue executing. – deceze Sep 18 '18 at 11:03
  • You are thinking in the correct question. you should wrap any code that depends on the async function in a callback or a promise and should be executed only async is done. You can also use await inside the function. Its like event based programming. – Seeni Sep 18 '18 at 11:05
  • @deceze https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call might be a good duplicate aswell – tkausl Sep 18 '18 at 11:07

0 Answers0