Async programming in javascript

Concurrency vs Parallelism

  • Concurrency is dealing with multiple things at once. Its is handled by processor through various threads.
  • Parallelism is doing multiple things at once. Generally handled through multiple processor cores.

Terminology

  • Single Thread vs Multi Thread.
  • blocking vs non-blocking.
  • synchronous vs asynchronous

So what happens if we block JavaScript??

There are few things that will block javascript

 

  • alert/prompt/confirm
  • synchronous HTTPRequest (not used these days)
  • fs.readFileSync
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log('Index: ' + i + ', element: ' + arr[i]);
  }, 3000);
}

Event Loop in JavaScript

  • What is a callback??
  • Why do we need callbacks??

      Callbacks

Callback Hell ??

Promises

Ok, Let's talk about Promises

Pros

  • Easy Chaining, sequential tasks.
  • Error Handling
  • Composable

But we are still doing callbacks inside .then(callbackFn)

Can we do better ??

What we want??

let promise = fetch('/url');

//Somehow we don't need to do a .then() and get the result

console.log(promise.result)

But JavaScript is single threaded, we can't block.

Generators

function * genFunc(){
    let result = fetch('/url');

    // pause the execution
    yield result;
    // resume the execution

    return result;

}

Async/ Await

It is basically a thin layer of abstraction of Promises and Generators

        
        async function getUsers(){
            // Magic code
            let result = await fecth('/url');
        
            return result;
        }

Async programming in javascript

By Naveen Reddy

Async programming in javascript

  • 63