Sitemap
Sriram

Sriram

JavaScript Notes — 4

Concurrency, Sequential Execution, Promises, delete, .call(), .bind(), NaN, Undefined, null, try, catch, finally

12 min readJan 14, 2025

--

Press enter or click to view image in full size

JS creates the illusion that tasks are being performed parallely, but in reality, at one time, only one stuff is being executed. It is just that the switching between tasks happen very rapidly using Time Slicing. This is known as concurrency.

Concurrency can be handled on single processor but parallelism requires multiple processors. So, JavaScript supports Concurrency but not Parallelism.

Example to understand async behaviour of setInterval:

function helloSayer(times, name){
let count = 0;
let x = setInterval(()=>{ // When using setInterval, we must take its reference
count ++;
console.log('Hello ' + name);

if(count==times){
clearInterval(x);
}
}, 100);
}

helloSayer(3, 'Arnav'); // Line A
helloSayer(2, 'Prateek'); // Line B

The complete understanding of the example requires the knowledge of Callstack and MicroTask but for now we can understand the example like this:

When Line A runs, a countdown of 100s begins (timer1), but in between the control flow doesn’t stop and it reaches to Line B, and a separate countdown of 100ms begins (timer2). The function which was called in Line A has completed the wait of 100ms (timer1) and Hello Arnav gets printed. Then again a countdown of 100ms begins (timer3). Now, timer2 has completed and Hello Prateek gets printed. And a new countdown of 100ms begins (timer4). Now timer3 gets completed and similarly the execution keeps on going.

Output:
Hello Arnav
Hello Prateek
Hello Arnav
Hello Prateek
Hello Arnav
. . .

Sequential Execution in Asynchronous function

Understand this before:

function f1(callback){
console.log('This is function 1');
callback();
}

function f2(){
console.log('This is function 2');
}

f1(()=>{
console.log('This is the body of callback function')
f2();
})


/*

Outputs:


This is function 1
This is the body of callback function
This is function 2

*/

Now this:

function f1(cb1){
console.log('function 1');
setTimeout(()=>{
cb1();
}, 1000);
}

function f2(){
console.log('function 2');
}

f1(()=>{
f2();
});

/*
Output:
function 1 // immediately
function 2 // 1 sec after the above line gets printed
*/

Sequential Execution Using Callbacks:

function f1(cb1){
console.log('f1');
setTimeout(()=>{
cb1();
}, 1000);
}

function f2(cb2){
console.log('f2');
setTimeout(()=>{
cb2();
}, 1000);
}

function f3(){
console.log('f3');
}

f1(()=>{ // this block is callback of f1 // cb1
f2(()=>{ // this block is callback of f2 // cb2
f3();
});
});

/*


Output:
f1 // immediately
f2 // after 1s of above line (ie 1s after start)
f3 // after 1s of above line (ie 2s after start)

*/

Sequential Execution Using Promises and .then(), .catch():

function f1(){
return new Promise((resolve, reject)=>{
console.log('f1');
setTimeout(()=>{
resolve();
}, 1000);
});
}

function f2(){
return new Promise((resolve, reject)=>{
console.log('f2');
setTimeout(()=>{
resolve();
}, 1000);
});
}

function f3(){
console.log('f3');
}

f1()
.then(()=>{
f2()
.then(()=>{
f3()
})
})

/*


Output:
f1 // immediately
f2 // after 1s of above line (ie 1s after start)
f3 // after 1s of above line (ie 2s after start)

*/

Sequential Execution Using Promises and async await:

function f1(){
return new Promise((resolve, reject)=>{
console.log('f1');
setTimeout(()=>{
resolve();
}, 1000);
});
}

function f2(){
return new Promise((resolve, rejct)=>{
console.log('f2');
setTimeout(()=>{
resolve();
}, 1000);
});
}

function f3(){
console.log('f3');
}

async function func(){
await f1();
await f2();
await f3();
}

func();

/*


Output:
f1 // immediately
f2 // after 1s of above line (ie 1s after start)
f3 // after 1s of above line (ie 2s after start)

*/

Promise

We can create a Promise object using constructor of default Declared Promise Class which takes only one argument: executor function. The executor function takes two arguments: resolve callback function and reject callback function. The executor function runs as soon as the Promise constructor is called, even if no handlers like .then() or .catch() have been attached.

let x = new Promise ( func ); // 'func' acts as executor fn

function func ( resolve , reject ) {

}

Although more popular way is to create executor function at the time of creating Promise itself using Arrow Function. Like this:

let x = new Promise ( (resolve, reject) => {
//
}
);

Example to print a given name specified no of times:
f1() returns a Promise.

function f1(name, times){
return new Promise ((resolve, reject)=>{
let count = 0;
let x = setInterval(()=>{
count++;
console.log('Hello Mr', name)
if(count == times){
clearInterval(x);
resolve();
}
}, 100);
});
}

f1('Arnav', 2); /* Outputs:
Hello Mr Arnav
Hello Mr Arnav
*/

Extremely Important Note:

If we want the stuff written in .then() to run only after the promise has been resolved, we should only have function reference (ie name of an already defined function, definition of an arrow fn or definition of an anonymously defined fn) in .then() and this is the basis to achieve sequential execution.

And if we directly call the function, or write statements, inside .then() then it gets executed immediately without waiting for the associated promise to get resolved or get rejected and the returned stuff is sent to .then(). We can say that this type of execution is independent (this is not a technical term).

Example of sequential (assume f1 as defined in the previous example):

f1('Rama', 2)
.then(()=>{
console.log('Running after f1 has resolved');
});
/*
Output:
Hello Mr Rama
Hello Mr Rama
Running after f1 has resolved
*/

Another example of sequential:
Code C-1:

f1('Raman', 2) // returns a promise, we can apply .then on it or leave it
.then(()=>{ // we apply .then
f1('Sekhar', 2) // will also return promise
.then( ()=>{ // .then applied on the promise
f1('Gaurav', 2); // again promise, but we leave
} );
});
/*
Outputs:
Hello Mr Raman
Hello Mr Raman
Hello Mr Sekhar
Hello Mr Sekhar
Hello Mr Gaurav
Hello Mr Gaurav */

Notice that this block of code is not sequential:
Code C-2:

f1('Raman', 2)
.then( ()=> {
f1 ('Sekhar', 2); // line a
} )
.then( ()=> { // line b .then() is not being applied to the promise of line a
f1 ('Gaurav', 2);
} )
.then( ()=> {
f1 ('Arnav', 2);
} )

f1 of line a simply stops after executing.

In Code C-1, we were applying .then inside the block of parent .then. But in Code C-2, that is not the case. So, for that, we will have to use return .

Corrected code C-2:

f1('Raman', 2)
.then( ()=> {
return f1 ('Sekhar', 2);
} )
.then( ()=> {
return f1 ('Gaurav', 2);
} )
.then( ()=> {
return f1 ('Arnav', 2);
} );

/*
Outputs:
Hello Raman
Hello Raman
Hello Sekhar
Hello Sekhar
Hello Gaurav
Hello Gaurav
Hello Arnav
Hello Arnav
*/

Good example of independent execution:

function f1(name, times){
return new Promise ((resolve, reject)=>{
let count = 0;
let x = setInterval(()=>{
count++;
console.log('Hello Mr', name)
if(count == times){
clearInterval(x);
resolve();
}
}, 100);
});
}

f1('Arnav', 3)
.then( f1('Prateek', 2) )
.then( f1('Rishav', 2) )

We have not passed reference of a function inside .then (like name of an already defined function, or an anoymous function or an arrow function) but have actually called the function which executes the function immediately without waiting for the parent promise to get resolved.
And similarly in next .then(), f1 is called immediately.
So, none of the promises waits for any other to get resolved first. They all are running immediately.

Output:

Hello Mr Arnav
Hello Mr Prateek
Hello Mr Rishav
Hello Mr Arnav
Hello Mr Prateek
Hello Mr Rishav
Hello Mr Arnav

Using async we could have seen similar independent execution, if we would have done:

async function task() {
f1('Arnav', 3);
f1('Prateek', 3);
f1('Raghav', 3);
}

task();

Output:

Hello Mr Arnav
Hello Mr Prateek
Hello Mr Rishav
Hello Mr Arnav
Hello Mr Prateek
Hello Mr Rishav
Hello Mr Arnav

If we have a Promise object, we can await that Promise object.

If a function func1 is returning a promise object, we can add the keyword await before func1 to await the returned object, which means the code execution will pause until the promise gets resolved or rejected.

Or, we can say that await keyword before a function means, we are applying await on the promise returned by the function.

await keyword can only be used inside an async function and also never in global scope.

function f1(name, times){
return new Promise ((resolve, reject)=>{
let count = 0;
let x = setInterval(()=>{
count++;
console.log('Hello Mr', name)
if(count == times){
clearInterval(x);
resolve();
}
}, 100);
});
}

async function task() {
await f1('Arnav', 3);
await f1('Prateek', 3);
await f1('Raghav', 3);
}

task();

Outputs:

Hello Mr Arnav
Hello Mr Arnav
Hello Mr Arnav
Hello Mr Prateek
Hello Mr Prateek
Hello Mr Prateek
Hello Mr Raghav
Hello Mr Raghav
Hello Mr Raghav

Que. Okay, so, await keyword should only be used inside an async function. But if await is being applied on a function. Should that function be async in nature?

Ans. Yes, because await is applied on a promise, and when we do apply await over a function, it means we are applying await over the promise which is being returned by the function. And if a function is returning a promise we should use async keyword.

In fact, async keyword denotes that the function will return a promise.

We saw that await cannot be used in a global scope. But although, the global scope in JS is synchro, it uses event loop to handle asynchro commncn then why not? Well because if we apply await there, the whole JS itself would stop. . . something like that. It can be difficult to deal with it, but modern version of node allows us to use await in global scope.

async func f1(){
// . . .
}
f1(); // async func
f2(); // regular func

Both the functions run independently of each other.

Let’s say we have multiple functions and some are in group1 and some in group2.
And now we want those two groups of functions to run independently in themselves but sequentially to other.

For eg, we want the group of (f1, f2, f3) to run independently and when they all have finished, we want the group of (f4, f5, f6) to run independently.

Get Sriram’s stories in your inbox

Join Medium for free to get updates from this writer.

We can think to use Promise.all like:

await Promise.all([f1, f2, f3]);

But it’s not ideal because if any one rejects, everything will stop. So, it’s better to use Promise.allSettled( [ ] );

await Promise.allSettled( [f1(), f2(), f3()] );

console.log('First group completed');

await Promise.allSettled( [f4(), f5(), f6()] );

delete keyword

delete keyword in JS is used to delete property of an object and not to delete variables which have been defined using let , const , or var . When we apply delete over those variables, it evaluates to false without returning anything and code execution moves ahead.

Note: To access property of an object, we need to provide reference to the parent object.

Important example:

let obj = {
a: 'wow',
b: 'not wow'
};

console.log(a); // Reference Error
console.log(obj.a); // wow

console.log(obj); // { a: 'wow', b: 'not wow' }

delete obj.a;

console.log(obj); // { b: 'not wow' }

Important example:

(function(x){
delete x; // delete on usual variable. evaluates to false. happens nothing. code execn moves ahead.
return x;
})(5);

// Outputs 5

.call( ) and .bind( )

.call() method is used on a fn while calling it to specify that this of the fn will refer to which object.

Syntax:

func.call(obj, x, y, z) ;
// `this` inside `func` refers to object `obj` and x, y, z.. are arguments

Example:

let obj1 = {
name: 'Ram',
age: 21
};

let obj2 = {
name: 'Keshav',
age: 22
};

function func(x){
console.log(`My name is ${this.name} and my age is ${this.age}`);
console.log(`My rating on leetcode is ${x}`);
}

func.call(ob1, 1400);
func.call(obj2, 1500);

Output:

My name is Ram and my age is 21
My rating on leetcode is 1400
My name is Keshav and my age is 22
My rating on leetcode is 1500

Note: Since .call() is used on a func while calling it, we can use it with IIFE also.

Example of IIFE with .call():

let obj1 = {name: 'Home', age: 32};
(function(){
console.log(this.name);
}).call(obj1);

// Outputs: Home

.bind() is used to create a new fn from an existing fn and binds it to an object, ie this inside the function only refers to that object.

Example:

function func1(){
console.log(`Hello, ${this.name}`);
}
let obj1 = {name: 'Keshav', age: 22};
let obj2 = {name: 'Gaurav', age: 24};
let func2 = func1.bind(obj2);
func2();

// Outputs: Hello, Gaurav

Note: If we try to use .bind() method on an arrow function, that doesn’t work. Because, this inside arrow function always refers to the object, inside which it was defined and we can’t change that.

Comma operator:

return func1(), func2(), func3();
// func1 runs, then func2, then func3 and only value of func3 is returned.

While defining a function, we don’t need to describe how many arguments it will take. We can pass any no of arguments to it, which can be accessed using arguments array.

Example:

function fun(){
console.log(arguments[2]); // Output: cake
}
fun('apple', 'banana', 'cake', 'donut');

NaN, Undefined, null

NaN
Invalid or Unrepresentable number.
Type: Number
Examples:

0/0
Number("hello")
"apple" - 5
5 * undefined
Math.sqrt(-1)
NaN + 5
NaN - 5
NaN * 5
NaN / 5

Undefined
Variable not assigned value yet.
Or, stuff returned from a fn of no return type.
Type: Undefined
Examples:

let x; console.log(x); // undefined

let obj = {a : 10};
console.log(obj.b); // undefined

let arr = [5, 10, 15];
console.log(arr[3]); // undefined

function func(){
}
console.log(func()); // undefined

null
Special value which can be assigned explicitly to variables to denote that they are empty or that they point nowhere.
Type: null
Example:

let x=null; console.log(x); // null

try, catch, finally

A block of code which can produce error, we add that inside try block
Whether error occurs due to expected reasons (handled using throw) or unexpected reasons, we handle them in catch block and run different code.
The error object in the argument of catch block gets overriden by the error object sent by throw.

finally is used to run codes after try, catch have executed.

Please note that throw or any other error will stop the execution of other lines in the try block immediately, and move the control to catch block.

Importance of throw: Use it when you know that by default JS would not be able to know the exact reason of the error.

Example:

function loginUser(username, password) {
try {
if (!username || !password) {
throw new Error("Username and password are required");
}
console.log("User logged in successfully");
} catch (error) {
console.log("Login failed: " + error.message);
}
}

loginUser("", "password123");
// Output: "Login failed: Username and password are required"

While resolving a promise, we can also send some parameter for the .then() handler.

function func(){
return new Promise((resolve, reject)=>{
resolve('Rama');
});
}

func().then(x){
console.log(x); // Outputs: Rama
}

Some additional notes on Asynchronous operations

Note 1:
1. A macrotask runs
2. Check if any new microtask has been added. If yes then execute them first.
3. Similarly proceed with next macrotasks.

Note 2:
setTimeout() starts its timer immediately and contents inside it gets added to the macrotask queue, but the key point is that the callback function does not execute until the specified delay has passed [condn1] and the event loop has finished processing any higher-priority tasks (such as synchronous code and microtasks like Promises) [condn2].

Example:

console.log("Start timer...");

setTimeout(() => {
console.log("Timer finished!"); // Line A
func(); // Line B
}, 2000); // 2 seconds

console.log("While waiting for the timer to finish...");
// Line A and Line B will run only when the two conditions stated above will be satisfied.

Note 3:
Immediately resolved promises:
As we know even if an async function returns a plain value, it is still wrapped inside a promise.
Whether ther resolution of the promise happen after the remaining synchronous stuff depends on the fact that if the function is returning a synchronous stuff like, regular function calls, returning values, objects etc or an asynchro stuff. If synchro, then the resolution happens immediately and resolution takes place before next synchronous tasks.

Example:

async function x (){
return 5;
}
console.log('a');
console.log(x());
console.log('b');

/*

Output:
a
5 // Immediately resolved promise
b

*/

Other example:

async function x (){
let y = await client.connect(); // asychro stuff in mongodb
// not the complete code. just for understanding
return 5;
}
console.log('a');
console.log(x());
console.log('b'):

/*

Output:
a
Promise { <pending> }
b

*/

Note 4:
Even for an immediately resolved promise
, the behavior of await introduces a scheduling step that ensures the subsequent code after the step of resolution runs asynchronously.

Or if we are handling promises using .then() , .catch() , we can say that even if a promise is immediately resolved, it does not execute its .then handlers until all the synchronous codes in the call stack finishes executing.

i.e. the line where a promise is called, that step is synchronous in nature. But, handling of that promise is asynchronous in nature.

Example:

async function async1(){          // 1.
console.log('async1 start'); // 2.
await async2(); // 3.
console.log('async1 end'); // 4.
}

async function async2(){ // 7.
console.log('async2'); // 8.
}

async1(); // 11.
console.log('hello'); // 12.

/*

Output:
async1 start
async2
hello
async1 end

*/

Explanation:

Line 11 runs. Which triggers the execution of function async1.

Line 2 runs. [Outputs: async1 start]

Line 3 runs. It knows it has to await the stuff returned when async2(). async2() will run.

Line 8 runs. [Outputs: async2] Promise of this block is immediately resolved since there was nothing asynchro.

Control goes back to Line 3. await sends all the remaining code of the current function to Microtask. Now we cant move forward with the execution of async1 untill all the synchronous tasks (like, line 12) in the main call stack has been finished.

Line 12 runs. [Outputs: hello]

Now all the synchronous tasks in the main stack has been finished. We can proceed with the execution of the microtasks (only line 4 is in microtask).

Line 4 runs. [Outputs: async1 end]

--

--