0

I am writing an express web application

I need to write the body of post request into disk, but the returned promise would have no use for me.

Is it necessary to await or attach then function to the returned promise?

import { promises as fs } from 'fs';
import express from 'express';

const app = express();

app.post('/', (req, res) => {
  fs.writeFile(`record/${req.body.name}.json`, JSON.stringify(req.body));
  res.send(`Hello World`);
});

app.listen(8080);
Max
  • 414
  • 1
  • 4
  • 12
  • Not at all, since your response doesn't rely on the promise being fulfilled. –  Jun 02 '20 at 12:10
  • 1
    You don't have to wait for the `Promise` to `resolve` or `reject`, however, you should handle error cases and return those back to the caller instead of making it feel like all requests succeed. – goto Jun 02 '20 at 12:12
  • Only needed if error needs to be handled – kewlashu Jun 02 '20 at 12:13
  • 1
    By the way, you should at least have the `.catch` handler even if you don't need it - unhandled promise rejections will cause issues and break your app. – goto Jun 02 '20 at 12:18

1 Answers1

1

No, you dont have to do anything with the returned promise, just like every non-async function it will be executed even if you ignore the return value, but there are some things you have to keep in mind:

if you dont wait for the promise to resolve or reject, the following actions, such as your res.send('Hello World'); most likely will be executed before the async operation is done. It depends on your application if this is a problem or not.

You also cant handle possible exceptions that might occur within the async function if you dont have a catch block, therefore your whole application might crash when running into an unhandled exception.

Howäms
  • 141
  • 4