Home > Software design >  Can we return from an express call before a promise resolves?
Can we return from an express call before a promise resolves?

Time:09-30

Can we return from an express function call request before a promise within the function is completed ?

To be more precise, I have a route that when called will make an insert to the database. I am using typeorm as the ORM library to help this. Now, in order to make the application faster, I would like to return the request to the client even before the promise finishes.

I have provided a minimal example in the codeblock below.

app.get('/', (req, res) => {
  const user = new User();
  user.firstName = "Timber";
  user.lastName = "Saw";
  user.age = 25;

  // There is no await here. This is an asynchronous process.
  repository.save(user);
  res.send('Hello World!')
})

I know that this User object will get saved anyways. However I'm more worried regarding any potential problems with Node & Express if being done this way such as memory-leak?

Additional Information: If for some reason there is an error during saving, that is OK if the data is not written.

CodePudding user response:

The async call will get put in the node event loop like any other call and will resolve when it can as you were able to observe in your application. There shouldn't be any concern with a memory leak as this is how asynchronous calls are meant to function.

The main draw backs are you are returning a success status code to the user without actually knowing there is a success and the eventual consistency the user will experience. If you are ok with those then there is no reason to not 'return' early.

CodePudding user response:

You can use promise to send response (error handing part is referenced by https://expressjs.com/en/guide/error-handling.html)

example:

app.get('/', (req, res, next) => {
  const user = new User();
  user.firstName = "Timber";
  user.lastName = "Saw";
  user.age = 25;

  repository.save(user)
    .then((_) => {
      res.send('Hello World!')
    })
    .catch((err) => {
      next(err)
    })
})
  • Related