Let's say p
is an object of type Promise
. A promise is usually returned by a function that started an asynchronous operation. The function returns (the promise) immediately while the asynchronous operation is still running in background.
The promise object is used by the calling code to know when the asynchronous operation completes.
This can be done in two ways:
Using .then()
/.catch()
. This lets the main script continues and when the asynchronous operation completes a callback provided by the main script is invoked to learn about the way the promise has been fulfilled.
p.then((v) => console.log(`the async operation completed successfully and returned '${v}'`))
.catch((err) => console.log(`the async operation failed with error: ${err}`));
Using await
and try/catch
. This way the main script is paused until the asynchronous operation completes. It resumes after the await
statement on success or with the catch
block if the async code throws an exception (the promise is rejected).
try {
v = await p;
console.log(`the async operation completed successfully and returned '${v}'`);
} catch (err) {
console.log(`the async operation failed with error: ${err}`);
}
Neither of these methods affects the way the async operation is executed. It does its job in the background and, at some point, it completes (with success or failure).
If neither of these synchronization methods is used then the main code loses any way to learn about the faith of the asynchronous operation.
If the async operation completes with success, nobody knows when this happens and the value it returns is lost.
If it throws an exception then there is no way to catch it and, at least in Node.js, it terminates the execution of the entire script (because it is an unhandled exception and the interpreter does not know if it's safe to continue in such situations.)
Using one of the methods above, when an exception is thrown by the asynchronous code, the handler registered with .catch()
(in the .then()/.catch()
method) or the code block after catch(err)
(in the await/try/catch
method) is executed and the exception is passed to it (as err
). It's up to these pieces of code to terminate the execution of the program or log the error and continue (as they do in my examples above).
Read more about promises and await