JS: Intro to promise, async, non-blocking, event loop

By Xah Lee. Date: .
work in progress

Parallel computation, concurrency, thread, non-blocking, event loop

in programing, lets say you have functions fa fb fc.

normally you run them in sequence. when fa is finished, it runs fb. when fb is finished, it runs fc.

but sometimes, some function takes a long time, you want it to run, but you also want to run the rest of your program, if it does not depends on it.

let's say your functions are

the f_b_1 takes a long time. but f_a_2 doesn't depend on it.

So your program now have 2 independent lines of logic. One is related to the database, the others are not.

you want to run your program in parallel, so while it is getting stuff from database, you can still run the rest.

this is the concept of parallel programing, and concurrency, and thread.

What is parallel programing, concurrency, thread

Parallel computation is when many independent tasks run at the same time. This is the most simple situation.

Concurrency is like parallel computation, but the tasks are not totally independent, some task may need to know the result from another task. You have the issue of which first have a result, and communication between tasks. Alternatively you might say, some of them need to share memory or state. Or, you might have each task send messages in some way to other, or request info from another. Many different approaches.

What is a thread

thread is operating system's feature, or programing language's feature, to allow you to do parallel computation or concurrent tasks. Exactly are they parallel (independent tasks) or dependent tasks (concurrency) depends on the operating system and programing language.

Illusion of parallel or concurrent

note, when you have 2 operating system threads, on a single core cpu, they don't actually run in parallel, but the operating system quickly switching between them, so we have the illusion that they are running in parallel or concurrent.

IMPORTANT. Whether they are actually running at the same time, doesn't matter. for programers, we just care, that the tasks are not waiting for the other.

This is an important aspect of JavaScript Event Loop.

What is asynchronous

Asynchronous code/function/operation means the operation is running concurrently or in parallel, or the illusion of. (more precisely, tasks are not waiting for other tasks.)

Asynchronous operation is also known as non-blocking operation.

What's event loop

JavaScript is technically single-threaded, meaning, JavaScript code never truly run in parallel, but not exactly, since browser can fetch html and render it or request images, while JavaScript code runs at the same time.

The JavaScript event loop is the runtime mechanism that lets single-threaded JavaScript do asynchronous/non-blocking operations.

What is non-blocking function

A non-blocking function is a function that is set aside to run after the rest of the code finishes. (technically, after the JavaScript “stack” is empty.) Basically, Non-blocking function creates the sense that it is running in parallel, via JavaScript event loop.

Note, JavaScript in 2015 does not have many non-blocking functions. You have setTimeout, setInterval, XMLHttpRequest, and few more. But in server side JavaScript, such as node.js, almost every function is non-blocking. So the callback-hell mostly happen on server side JavaScript code. Since promise was created in 2015, there are more non-blocking functions, many of them return a promise. e.g. fetch.

What is a promise

Purpose of promise

Promise is a JavaScript object that is designed to let you work with non-blocking functions such as setTimeout in a linear way. (without nesting the callback functions in the body.)

In particular, when you have a sequence of non-blocking functions and want to chain them (i.e. call one after the other only when successful), promise allows you to write them without nested code.

Callback hell

Complicated nested code with callbacks is known as callback-hell. In that situation, it is difficult to see which function is in which argument of which function.

// Nested callbacks.
task1(
 (res1) => {
  task2(
   (res2) => {
    task3(
     (res3) => {
      console.log("All done:", res1, res2, res3);
     },
     (err3) => console.error("task3 failed:", err3),
    );
   },
   (err2) => console.error("task2 failed:", err2),
  );
 },
 (err1) => console.error("task1 failed:", err1),
);

Promise does not create non-blocking operation

JavaScript promise does not create non-blocking operation. Whatever code you put inside promise, it must already be non-blocking such as setTimeout. There is no way to turn a blocking code into non-blocking. If you want parallel computation, you need to run Web Workers.

Example. callback vs promise

/*
demo the difference between callback vs promise version.

tasks1 tasks2 tasks3 are wrappers to js non-blocking functions, each syntax takes callback functions.

we want to do
tasks1 → tasks2 → tasks3.
if task1 is success, then do task2, etc.
*/

/*
task1(fSuccess, fFail)

fSuccess is a function.
fSuccess(output) is called if the job is successful.
The argument output is the output value of the job.

fFail is a function.
fFail(outputError) is called if the job failed.
The argument outputError is whatever was the error.
*/
function task1(fSuccess, fFail) {
 setTimeout(() => {
  console.log("task1 done");
  fSuccess("result1");
  // or: fFail("error1");
 }, 500);
}

function task2(fSuccess, fFail) {
 setTimeout(() => {
  console.log("task2 done");
  fSuccess("result2");
  // or: fFail("error2");
 }, 500);
}

function task3(fSuccess, fFail) {
 setTimeout(() => {
  console.log("task3 done");
  fSuccess("result3");
  // or: fFail("error3");
 }, 500);
}

// s------------------------------

// Nested callbacks.
task1(
 (res1) => {
  task2(
   (res2) => {
    task3(
     (res3) => {
      console.log("All done:", res1, res2, res3);
     },
     (err3) => console.error("task3 failed:", err3),
    );
   },
   (err2) => console.error("task2 failed:", err2),
  );
 },
 (err1) => console.error("task1 failed:", err1),
);

/*
task1 done
task2 done
task3 done
All done: result1 result2 result3
*/

// s------------------------------
// promise version

// Promise wrappers
const p1 = () => new Promise((resolve, reject) => task1(resolve, reject));
const p2 = () => new Promise((resolve, reject) => task2(resolve, reject));
const p3 = () => new Promise((resolve, reject) => task3(resolve, reject));

p1()
  .then((res1) => p2().then((res2) => ({ res1, res2 })))
  .then(({ res1, res2 }) => p3().then((res3) => ({ res1, res2, res3 })))
  .then(({ res1, res2, res3 }) => console.log("All done:", res1, res2, res3))
  .catch((err) => console.error("Failed:", err));

/*
task1 done
task2 done
task3 done
All done: result1 result2 result3
*/