An Example of a Non Blocking Process in JavaScript
Learn how to create a non-blocking process using Callback and Promise by example

JavaScript is a synchronous programming language. This means that it will execute your code block by order from top to bottom. But thanks to the JavaScript Event loop, we are able to do non-blocking processes by using a callback function and a promise function.
Here are some examples.
Callback Function
// Example Parameter Function
const parameter = {
firstName: 'John',
lastName: 'Doe'
}// Example callback function (will run after delay function finish)
const callBackFunction = (result) => {
console.log(result)
}// Example slow process or API call Function
const delayFunction = (callBack, parameter) => {
// For replicate delay we use setTimeout as example
setTimeout(() => {
// Example slow process or api call return
const result = `${parameter.firstName} ${parameter.lastName}`
// Triggering the callback function after getting the result
callBack(result)
},1000)
}console.log('start')
// Run delay function
delayFunction(callBackFunction, parameter)
console.log('finish')// Output:
// Start
// Finish
// John Doe
Promise Function
// Example Parameter Function
const parameter = {
firstName: 'John',
lastName: 'Doe'
}// Example callback function (will run after delay function finish)
const callBackFunction = (result) => {
console.log(result)
}// Example slow process or API call Function
const delayFunction = (parameter) => {
return new Promise((resolve) => {
// For replicate delay we use setTimeout as example
setTimeout(() => {
// Example slow process or api call return
const result = `${parameter.firstName} ${parameter.lastName}`
// Triggering the resolve promise after getting the result
resolve(result)
},1000)
})
}console.log('start')
// Run delay function
delayFunction(parameter).then(callBackFunction)
console.log('finish')// Output:
// Start
// Finish
// John Doe
The benefit of learning and using the non-blocking approach is you can reduce the JavaScript main thread process and boost your code performance, so your thread doesn’t get blocked and still run through every process left.
After all the process left has been done, JavaScript will check the Event loop to see whether the callback has already finished or not. When finished, it will run the callback function.