Duccio
Duccio

Reputation: 163

Cleanest way to use async results in Javascript

Coming from C++ and Python, I still struggle with Javascript asynchronous ubiquity. Sometimes it's very useful, but other times I just don't see how to fit it in without writing terrible code.

I have a Node.js + Express CRUD setup, and I have to do some basic check-ups before continuing with the request. I want to check that http POST fields match with database fields before running the final query. I cannot declare it an async function and use await as it must match a given Interface.

showColumns(dbTable) returns a db premise with a SHOW COLUMNS query.

The only solution that I found is:

database.showColumns(dbTable).then((columns)=>{

  //But do I really need to put all my logic inside a then???

  let row =  Object.keys(req.body).filter({}.hasOwnProperty.bind(columns));
  //... all the rest of the logic goes here

});

In your opinion, what is the cleanest/most elegant way to solve that?

Upvotes: 3

Views: 82

Answers (2)

Nishant Dixit
Nishant Dixit

Reputation: 5522

You can use async/await for this.

(async function() {
    try {
        var columns = await database.showColumns(dbTable)
        let row = Object.keys(req.body).filter({}.hasOwnProperty.bind(columns));
    } catch (e) {
        console.log("Promise error");
    }
})

Upvotes: 1

justMe
justMe

Reputation: 664

database.showColumns(dbTable)
  .then(columns => this.handleColumns(columns))
  .then(parsedData => this.doSthElse(parsedData);

You can extract your logic to a seperate method. However, it must be called inside then as it is the callback triggered once your async operation is finished.

Alternatively, you might consider using generators, async/await functions or promises.

Upvotes: 3

Related Questions