0

I believe this is one of the most fundamental/beginner question in modern JavaScript. There are lots of similar questions present and I have gone through a bulk of it. But as I could not find an accurate answer, I am posting my problem in a fresh question.

I am using sequelize in a node and express app. Now, all of the query functions like findOne are async in nature. I have two functions,

function A(){
   B()
   .then((result:any) => {
       if(result){
           // Do something
       }
    });
}

async function B(){
   sequelizeModel.findOne({where: {<col>:<val>}})
   .then((result:any) => {
       if(result === null){
           return true;
       }
       else{
           return false;
       }
   })
   .catch((error: any) => {
       console.error(error);
       return false;
   });
}

B() checks into the DB to see if a particular data row is present or not. So, it will return the true/false. Based on that A() perform certain activity.

Now, B() is always getting result = undefined.

One solution is that,

function A(){
   B()
   .then((result:any) => {
       if(result === null){
           // Do something
       }
    })
    .catch((error:any) => {
         console.error(error);
    });
}

async function B(){
   return await sequelizeModel.findOne({where: {<col>:<val>}});
}

But is there any way so that I do not want to put the null checking logic inside A() and perform it within B(). (Possibly I am missing some vital understanding)

1 Answer 1

3

The function B() has to return the promise that you try to catch in the function A(), so, just return it from B() function.

The problem is that when you put B().then()... Javascript expects that B() function returns a promise, in fact B() function as an async function returns a promise, but it does not have any return statement, so it resolves as undefined.

function A(){
   B() // Handling the promise returned by B()
   .then((result:any) => {
       if(result){
           // Do something
       }
    });
}
    
function B(){
       return sequelizeModel.findOne({where: {<col>:<val>}}) //Returns the promise that A() function will handle.
       .then((result:any) => {
           if(result === null){
               return true;
           }
           else{
               return false;
           }
       })
       .catch((error: any) => {
           console.error(error);
           return false;
       });
    }

And the async word is not necessary in that context, because it is returning the promise.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.