2

Most of the articles mention that await is a replacement for then. However, I can't find a way to do the approach below by using await since it will defer execution until run query finishes. Just curious, is there a way?

this.database
    .run(query, bindings)
    .then(result => this.ws.send(result))
    .catch(err => this.ws.error(err));
return reply.code(202).send();
Cemre Mengü
  • 18,062
  • 27
  • 111
  • 169
  • No, in this case `async`/`await` is not really helpful. – Bergi Dec 25 '18 at 17:59
  • 1
    Btw, I would suggest to use [`.then(…, …)` instead of `.then(…).catch(…)`](https://stackoverflow.com/q/24662289/1048572) here. – Bergi Dec 25 '18 at 18:00

1 Answers1

4

The fact that you can't directly use async/await here should tip you off that what you have here isn't such a good idea. It's fire-and-forget code, which is rarely a good practice.

However, if that's actually what you want to do, one option available is to put the async/await in a separate method.

Separate method:

async runQuery(query, bindings) {
    try {
        const result = await this.database.run(query, bindings);

        await this.ws.send(result);
    } catch(err) {
        await this.ws.error(err);
    }
}

Main code:

this.runQuery(query, bindings);

return reply.code(202).send();
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thanks for the suggestion. I made it fire-and-forget since I dont know how long the query execution will take. Any replacement suggestions? – Cemre Mengü Dec 25 '18 at 17:21
  • 1
    @Cemre If you *want* fire-and-forget, and `reply` immediately, then it's the right code. Also I wouldn't strictly say that it's "forgetting", as you still use the result of the query to send it over the websocket. Your code is fine. – Bergi Dec 25 '18 at 18:02