JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

An Example of a Non Blocking Process in JavaScript

Learn how to create a non-blocking process using Callback and Promise by example

Hans Sagita Soegiarto
JavaScript in Plain English
2 min readMar 5, 2021

--

Photo by James Harrison on Unsplash

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.

Conclusion

That’s it and if you found this article helpful, let us know in the comments. You can also follow me on Medium and LinkedIn

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

No responses yet

Write a response