I am trying to scale my nodejs app so that it can efficiently handle multiple requests at the same time. One way of achieving this is through code optimization and i wanted to know how I can make time consuming requests async, are promises the only way? or is there another mechanism to achieve the same?
I have already used promises for async tasks but as far as i understand promises, the truly async part is the then and catch handlers. When one creates a promise the executor function will be executed by the main thread until it does some async task (setTimeout, etc).
Sample code of send email
app.route('/api/contact/sendEmail')
.post((req, res) =>{
sendEmail(req).then( () =>{
res.status(200);
res.json({
sent: true
});
}).catch(emailError=> {
//Custom error send bad request.
if(emailError.code === 900) {
res.status(400);
res.json({
errorCode: emailError.code,
message: emailError.message
});
}else {
res.status(500);
res.json({
errorCode: emailError.code
});
}
});
});
The thread is not blocked to send the response but until the sendEmail does not reach the actual async part, the main thread will be blocked