Home > Enterprise >  NodeJs: Promise always returns undefined
NodeJs: Promise always returns undefined

Time:03-05

So I have the following promise that is supposed to go inside my sqlite database and tell me if there is a match. Even if the variables are correct it always returns undefined.

var checkLoanable = function(bookID){
    return new Promise((resolve, reject)=>{
        
        db.run('SELECT * FROM book WHERE id=?',[bookID],(err,row)=>{
            if (err) {
                console.log("error")
                reject();
                }
            if(row){
                
                if(row.loanable==0){
                    console.log("not loanable")
                    reject();
                        
                }
                console.log("success")
                resolve(row);
            }else{
                console.log("undefined")
                reject();
                    
            }
            console.log("End of promise")
        });
    
    })
}

This is the call of the function

await checkLoanable(bookID)
        .then(()=>{console.log("success")})
        .catch(()=>{
            res.status(422)
                .setHeader('content-type', 'application/json')
                .send({ message: "Failed to add loan: book is not loanable!"});
            
        });
        console.log("after promise");
        

The await is inside an async function and after tests I did it does wait for the promise to end and then continues the code. I can't figure out why its always undefined though. Thank you in advance for any help.

CodePudding user response:

run() is used for inserting and updating rows.

For getting a single row use db.get().

db.get('SELECT * FROM book WHERE id=?', [bookID] , (err,row) => { });

At least if you are using the npm/sqlite package.

CodePudding user response:

Do not mix async/await and Promise chain use one of them.

Either with try...catch or Promise..then..catch

try {
  const book = await checkLoanable(bookID);
  res.json(book);
}catch ({message}) {
  res.status(422).send(message);
}

// or
checkLoanable(bookID)
  .then((book) => {res.json(book);})
  .catch(({message}) => {
    res.status(422).json({ 
      message: "Failed to add loan: book is not loanable!"
    });
  });

For the example if you use something like this

const myPromise = () => new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

(async () => {
  const result = await myPromise().then(data => {
    console.log({data});
  });
  console.log({result});
})();

Result would be

{data: 'Success!'}
{result: undefined}

Not both get values at the same time.

  • Related