Member-only story
Better JavaScript — Async Code
Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at ways to improve our JavaScript code.
Error Handling with Async Code
Like synchronous code, async code errors also need to be handled.
Handling async code errors may be trickier than synchronous code.
Synchronous code errors can be caught with a try-catch block:
try {
f();
g();
h();
} catch (e) {
//...
}
We catch the errors in the catch
block.
And e
has whatever is throw in the code in the try
block.
Async code comes in a few forms.
If it’s a callback, then some may send the error with the callback.
For instance, Node style callbacks send the error:
fs.readFile('/foo.txt', (err, data) => {
if (err) {
throw err;
}
console.log(data);
});
In the fs.readFile
method, err
has the error that’s set when there is one.
We can check for the err
value and do something.