Reputation: 1056
Let's say we have a controller which fetches data from 3rd party service, save that data to db and send response to the client:
const findUser = async (req, res, next) => {
if (req.params.username) {
const resp_ = await fetchFunction (req.params.username)
/* This part is where I have problem*/
Option 1:
await db.save(resp_);
Option 2:
db.save(resp_);
Option 3:
db.save(resp_).then(param => /*Do nothing*/ clg(param)).catch(err => clg(err))
res.json(resp_)
}
};
I don't want to block async flow in this controller if I use option 1 it is going to wait for db.save() function to finish and I think there is no way I can implement this behaviour with async/await. Which option is preferable way or are there any other way I can sen response to client without blocking flow.
[Edit]: Option 2 is kind a silly implementation but I just added to understand differences.
Upvotes: 0
Views: 27
Reputation: 12552
If you want to do those operations simultaneously then you can use Promise.all()
which parallelise the functions.
like,
await Promise.all([db.save(resp_), Promise.resolve(1).then(()=>res.json(resp_))]);`
Or, If you don't care if the data gets saved or not then Option 2 is not that bad of a choice.
Upvotes: 1