Are promises guaranteed to be executed?
First off, this is a bit of terminology correctness, but promises don't "execute". Asynchronous functions execute and they create promises that help you monitor their completion. You aren't calling a promise here. You're calling a function that returns you a promise.
is it ABSOLUTLY GUARANTEED that logIntoDatabase is going to execute?
Yes, if logData(...)
is called, then logIntoDatabase()
will always execute as the very first line in that function in both your first and second code examples.
Your method like this:
async logData(request, response) {
await logIntoDatabase("something happened");
response("log successful");
}
is essentially equivalent to this (assuming logIntoDatabase()
returns a promise and doesn't throw synchronously):
logData(request, response) {
return logIntoDatabase("something happened").then(() => {
response("log successful");
});
}
As such you can see that the very first line to execute inside logData()
is your call to logIntoDatabase()
.
A full replacement for the async
function would be this:
logData(request, response) {
try {
return Promise.resolve(logIntoDatabase("something happened")).then(() => {
response("log successful");
});
} catch(e) {
return Promise.reject(e);
}
}
This covers other misbehaviors such as logIntoDatabase()
not returning a promise or throwing synchronously. But, even in this more complete analogy, you can see that logIntoDatabase()
is still guaranteed to be called.
In your 2nd code example:
async logData(request, response) {
logIntoDatabase("something happened");
response("log successful");
}
You are still guaranteed that logIntoDatabase()
will be called. But, this will differ in behavior from your version with await
in three ways:
response("log successful")
will always be called even if logIntoDatabase()
rejects.
response("log successful")
will be called BEFORE logIntoDabase()
finishes it's asynchronous operations.
The promise returned from logData()
will not have any connection to whether logIntoDatabase()
resolves or rejects. If neither logIntoDatabase()
or resolve("log successful")
throws synchronously, then the promise will be resolved with an undefined
resolved value. If either does throw synchronously, then the promise returned from logData()
will reject with the exception as the reason for the rejection.
So, your second example is analogous to this:
logData(request, response) {
try {
logIntoDatabase("something happened");
response("log successful");
return Promise.resolve();
} catch(e) {
return Promise.reject(e);
}
}
And, you can see that logIntoDatabase()
is still guaranteed to always be called.