Javascript Antipatterns to be avoided

Callbacks, Promises, and Async await

I jumped on in the interview with MERN stack-based E-commerce project but, the interviewer started with javascript and I was rejected. I think I rushed with React and Node ignoring the richness of Javascript, but after reading these series you won't.

Is javascript synchronous or asynchronous, if one of these can we make it vice versa?

  1. Is javascript single-threaded or multi-threaded, if single-threaded how multiple requests are served?
  2. Explain Execution context wrt hoisting
  3. What are Closures and explain wrt setTimeout
  4. What are callbacks and how do event listeners use them using Event Loop
  5. Can you describe concurrency in Javascript?
  6. Mutability in JSON objects matters? and many more questions...

    and my expressions were😅🥲🙃😱😬🙄🤐

Understanding synchronous Javascript, but before that let's understand Promises

let promise = new Promise((resolve,reject) = > {
  // perform some tasks 
  const status = 'Task Done';
 if( status === 'Task Done') {
    resolve('Success');
  }
  else {
    reject('Failed');
  }
});

promise.then((message) => {
  console.log('In the then block message is' + message);
}).catch((message) => {
  console.log('In the catch block message is' + message);
});

In the real world, the comment performs some tasks is API calls to the backend. Interviewer: What is .then and .catch ?

They are callbacks😅

Interviewer: can you elaborate on what are callbacks?

Let's say your frontend is returning a JSON object of product

[
    {
        name: 'Clean Code in Javascript',
        category: 'Books',
        seller: 'ObjectId('giberish'),
        price: 9$,
        rating: 4.9,
        reviews: []
    }
]

Now if the seller of the product is editing its price to reflect changes in DOM, we need callback functions.

const getProduct = (id) => {
    fetch(`http://localhost:8081/product/${id}`);
    // show in DOM using React
}

const updateProduct = (id,callback) => {
    fetch(`http://localhost:8081/product/${id}`,{
        method: 'PUT',
        content-headers: 'JSON',
        body = {
            price: 19$
        }
    });
    callback();
}

getProduct(gibberish);

updateProduct(gibberish,getProduct);

So after a product is updated again get product is called to see new data on DOM. Later on these will be seen in componentDidUpdate using React.js.

Can promise be avoided?

using async and await

const updateProduct = async (id) => {
    await fetch(`http://localhost:8081/product/${id}`,{
        method: 'PUT',
        content-headers: 'JSON',
        body = {
            price: 19$
        }
    });
    getProduct();
}

Two Golden Rules for cleaner code

  • Replace Callbacks with Promises
  • Replace Promises with Async and Await

References

  1. Clean Code in Javascript
  2. Callbacks
  3. Promises
  4. Async-Await

I hope you have now understood Callbacks, Promises, and Async-Await in javascript. Threading in Javascript is discussed in next blog. Till then stay connected Twitter, Instagram.