3

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?

1
  • 1
    You can put all your logic inside an Async IIFE, like so: (async () =>{ /** your code **/ })(); Commented Aug 7, 2018 at 12:07

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

I find no point in splitting the code into multiple .then when there are only two async calls, and the latter solves the whole Premise. If you have a few single async functions to call, a chain of .then is nice and readable. But I don't believe that a long function with some more logic is more readable inside multiple .then()
Splitting into multiple then's makes sence if each one of them does a different asynchronous operation. My snippet was an example of how you can chain multiple async calls. Every then returns a promise.
1

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");
    }
})

2 Comments

Clever! It's definitely more readable than the .then, as the whole function can be wrapped without breaking it in the middle. Of course I assume it needs the "();" at the end to execute
You don't need to wrap function with "()" I did just because of I am defining anonymous function here You can remove if you are defining actual function with name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.