I want to start by saying that I understand quite well async in JavaScript by using promises (async/await) and callbacks.
The way I see it regarding Promises in Nodejs is that if you start using a Promise you have to keep using that flow until the end of the app, either by using Promise Chaining
or Promise.all()
etc. methods.
Let's take into consideration the following simple app:
require('http').createServer().on("request",
async (req, res) => {
// MY PROMISE
myPromise("error").then( event => console.log(event)).catch( error => console.log(error) );
// RUNS BEFORE THE PROMISE
console.log("1");
// RESPONSE SENDING
res.end("OK");
}
)
.listen(3000);
This is a simple example, but let's say that in the Promise we have to retrieve some info from the DB or anything else that takes a long time.
In case I don't use AWAIT
to block the loop until the promise is either resolved or rejected, the code will run on to the next line etc. Only later on the console.log
from the Promise will show up.
So by using AWAIT
I block the event loop and by not using it I dont get the info from the Promise.
Then why should I not use a sync code in the first place?
Is there another way to use Promises in an app?
Thank you!