how to make function synchronous in javascript

In JavaScript, by default, functions are synchronous which means they execute one after another in a sequential order. However, if the function contains any asynchronous operation like making an HTTP request or fetching data from a database, then that function becomes asynchronous.

To make a function synchronous in JavaScript, you can use either async/await or callback function.

Using async/await:

index.tsx
async function myFunction() {
  // perform synchronous tasks
  await someAsyncTask(); // wait for completion of asynchronous task before moving ahead
  // continue with remaining synchronous tasks
}
199 chars
6 lines

Using callback:

index.tsx
function myFunction(callback) {
  // perform synchronous tasks
  someAsyncTask(() => {
    // this callback will execute only after the completion of the asynchronous task
    // continue with remaining synchronous tasks
    callback();
  }); 
}
246 chars
9 lines

In both cases, the synchronous tasks will execute first and after the completion of the asynchronous task, the remaining synchronous tasks will execute.

gistlibby LogSnag