1.

Asynchronous JavaScript

Answer»

A number of Web API features now use asynchronous code for running, especially those that access or fetch a resource from external devices, for instance, retrieving files from the network, accessing some database and returning data to it, accessing a video stream from a webcam, or broadcasting the display to a VR headset. There are two ways in which asynchronous coding can be done in JavaScript:


  • Async Callbacks: When invoking a function, async callbacks are functions that are passed as arguments and begin executing code in the background. When the background code is finished, it runs the callback function to notify you that the work is complete or that anything interesting has occurred. Callbacks are a little out of date these days, but they're still utilised in a lot of older but still popular APIs. The second parameter of the addEventListener() method is an example of an async callback:
buton.addEventListener('click', () => {
alert('Button has been clicked!');
let paraElement = document.createElement('p');
paraElement.textContent = 'A new paragraph.';
document.body.appendChild(paraElement);
});

The first parameter specifies the type of event to be listened for, while the second specifies a callback function to be called when the event occurs. When we give a callback function as an input to another function, we are merely passing the function's reference; the callback function isn't immediately performed. It is asynchronously "called back" (thus the name) somewhere within the containing function's body. When the time comes, the contained function is in charge of calling the callback function.


  • Promises: Promises are a new async programming paradigm that you'll see in current Web APIs. The get() API, which is essentially a newer, more efficient version of XMLHttpRequest, is a nice example. Let's take a look at an example from our post Fetching data from the server:
fetch(items.json').then(function(res) {
return res.json();
}).then(function(json) {
let item = json;
initialise(item);
}).catch(function(e) {
console.log('Fetch error: ' + e.message);
});

Here, fetch() takes a single argument:  the URL of a network resource we wish to fetch and a promise is returned. A promise is an object that represents whether the async operation succeeded or failed. In a sense, it reflects a transitional condition. In essence, it's the browser's way of saying, "I promise to respond as quickly as I can," hence the name "promise."

Note: Pyramid of Doom, also known as Callback Hell, is an anti-pattern found in asynchronous computer code. It is a slang phrase for a large number of interconnected "if" statements or functions. A few callbacks appear harmless if you do not expect your application logic to become too sophisticated. However, as your project's requirements grow, you will quickly find yourself with layers upon layers of nested callbacks. The usage of callbacks makes writing and maintaining code more challenging. It also makes it more difficult to identify the application's flow, which is a debugging roadblock, hence the problem's well-known nickname: Callback Hell. An example of callback hell is given below:

fs.readdir(source, function (error, file) {
if (error) {
console.log(Problem occurred while finding file: ' + error)
} else {
file.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (error, value) {
if (error) {
console.log(Problem occurred while identifying file size: ' + error)
} else {
console.log(filename + ' : ' + value)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(error) {
if (error) console.log('Problem occurred while writing file: ' + error)
})
}.bind(this))
}
})
})
}
})


Discussion

No Comment Found