NodeJs:Promise 始终返回未定义

发布于 2025-01-11 14:39:34 字数 1270 浏览 0 评论 0原文

所以我有以下承诺应该进入我的 sqlite 数据库并告诉我是否有匹配。即使变量是正确的,它也总是返回未定义的。

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

这是函数的调用,

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

await 位于异步函数内部,经过我所做的测试,它确实等待承诺结束,然后继续执行代码。我不明白为什么它总是未定义。 预先感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里寻她 2025-01-18 14:39:34

run() 用于插入和更新行。

要获取单行,请使用 db.get()。

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

至少如果您使用 npm/sqlite 包。

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.

别念他 2025-01-18 14:39:34

不要混合使用 async/await 和 Promise 链之一。

使用 try...catch 或 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!"
    });
  });

例如,如果您使用类似这样的

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

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

结果,则不会

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

同时获取值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文