Home > Software engineering >  Is it a bad idea to explicitly ignore promises?
Is it a bad idea to explicitly ignore promises?

Time:02-11

I have an api call which triggers an async function doSomething. Inside this function I have another async function that creates a notification for the user but I do not want to wait for it until it is finished. So I removed the await statement. The code works but is this a bad idea or bad practice because I get a "Missing await for an async function call" warning.

    public async createNotification(createdStuff: CreatedStuff): Promise<void> {
        const userNotification = new Notifcation(..);
        await userNotification.save();
    }

    public async doSomething(): Promise<CreatedStuff> {
        const createdStuff = await this.createStuff();
        await createdStuff.save();

        // here I removed the await statement
        this.notificationService.createNotification(createdStuff);

        return createdStuff;
    }

CodePudding user response:

If createLogPlayNotification(...) rejects, you will run into an unhandledRejection event which you probably don't want as it will crash your app depending on your NodeJS version (see this link for more information).

This does not mean you have to await it, you can simply add a .catch-handler on the returned promise:

// ..
this.notificationService.createLogPlayNotification(loggedPLay)
                        .catch(err => {
                            // do something with err, e.g. log it
                         });
return createdStuff;
  • Related