In synchronous programming, the code is executed sequentially and blockingly. Synchronous execution of code means each line is executed one after another, and the next line executes once the previous one has finished. It means that if there is a time-consuming operation, the entire execution will be paused until it is completed.
console.log('One');
console.log('Two');
console.log('Three');
One
Two
Three
Asynchronous programming refers to executing code non-blockingly, allowing multiple operations to run simultaneously. Asynchronous code does not wait for an operation to complete before moving onto the next line. Rather, it initiates the operation and executes the subsequent code.
console.log('One');
// Wait for 1 seconds
setTimeout(() => console.log('Two'), 2000);
console.log('Three');
One
Three
Two
console.log("Before API call");
const response = fetch("URL");
console.log("After API call");
console.log("Before API call");
fetch("URL")
.then(response => {
console.log("Inside API callback");
});
console.log("After API call");
console.log("Before file read");
const data = fs.readFileSync("file.txt", "utf-8");
console.log("After file read");
console.log("Before file read");
fs.readFile("file.txt", "utf-8", (err, data) => {
console.log("Inside file callback");
});
console.log("After file read");
console.log("Before first API call");
const response1 = fetch("URL1");
console.log("After first API call");
console.log("Before second API call");
const response2 = fetch("URL2");
console.log("After second API call");
console.log("Before first API call");
fetch("URL1")
.then(response1 => {
console.log("Inside first API callback");
// The next code depends on the first response
console.log("Before second API call");
return fetch("URL2");
})
.then(response2 => {
console.log("Inside second API callback");
});
console.log("After first API call");