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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0