...

/

ES5, Promises and async/await Conclusion

ES5, Promises and async/await Conclusion

Learn the crucial nuances between the three different forms of asynchronous code we've covered so far.

We'll cover the following...

The Different Forms of Async Code

This is an excellent opportunity to observe the differences between the different forms of asynchronous code.

Here’s the code we started with, with error handling:

Press + to interact
onRequest((request, response) => {
try {
readFile(request.fileToRead, data =>
writeFile(request.fileToWrite, data, status =>
response.send(status)
)
);
} catch(err) {
console.log(err);
response.send(err);
}
});

Here’s the code transformed using Promises and ES2015.

Press + to interact
onRequest((request, response) =>
readFile(request.fileToRead)
.then(data => writeFile(request.fileToWrite, data))
.then(status => response.send(status))
.catch(err => {
console.log('Caught error:', err);
response.send(err);
})
);

And here it is using async/await. There are no special tools to work with errors here. We simply use a standard try/catch block.

Press + to interact
onRequest(async (request, response) => {
try {
const readFileData = await readFile(request.fileToRead);
const writeStatus = await writeFile(request.fileToWrite, readFileData);
response.send(writeStatus);
} catch(err) {
console.log('Caught error:', err);
response.send(err);
}
});

Discussion

Gaining experience with these different mechanisms reveals some insights into their strengths and weaknesses.

ES5

Standard ES5 code will callbacks is easily the most confusing form of code here. We have a pyramid of doom inside a try/catch block. It may not seem too complicated here; our pyramid is ...