Non blocking | blocking code example

Blocking code

In this example, the getUserSync function returns a user object from a hardcoded list of users. This function is blocking, because it executes synchronously and returns the result immediately.

const getUserSync = (userId) => {
  const users = {
    1: { name: 'John', age: 35 },
    2: { name: 'Jane', age: 28 }
  };
  return users[userId];
}

const user = getUserSync(1);
console.log(user);

Non Blocking code

In this example, the getUserAsync function returns a user object from a hardcoded list of users, but it executes asynchronously, using the setTimeout function to delay the execution of the callback function by 1 second. The getUserAsync function takes a callback function as its second argument, which is called with the user object once it has been retrieved.

const getUserAsync = (userId, callback) => {
  const users = {
    1: { name: 'John', age: 35 },
    2: { name: 'Jane', age: 28 }
  };
  setTimeout(() => {
    callback(users[userId]);
  }, 1000);
}

getUserAsync(1, (user) => {
  console.log(user);
});