Exceptions in asynchronous callbacks in JavaScript

Let, if the number of a non-existent array element is passed as the make parameter, then this is an exceptional situation. As you already know, exceptions thrown inside an async function cannot be caught with try-catch. In our case, an exception thrown inside make or a callback will not be caught:

try { make(10, function(res) { console.log(res); }); } catch(err) { // it won't get caught }

In the callback approach, they work as follows with exceptions: the result is sent to the first callback parameter, and the error is sent to the second. In this case, the error handling is as follows:

make(10, function(res, err) { if (!err) { console.log(res); // no error occurred, we output the result } else { console.log(err); // an error has occurred, we output its text } });

Let's rewrite our make function code as described:

function make(num, callback) { setTimeout(function() { let arr = [1, 2, 3, 4, 5]; let err; if (arr[num] === undefined) { err = 'elem not exists'; // an error text } else { err = null; // no error } callback(arr[num], err); }, 3000); }
enru