gpt4 book ai didi

javascript - 如何在 Sequelize Js 中使用 Promise 返回实体

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:20 24 4
gpt4 key购买 nike

var user =  db.User.find({ where: { username: username }}).then(function(user) {
console.log("Authenticate"+user.authenticate(password));
if (!user) {
return null;
} else if (!user.authenticate(password)) {
return null;
} else {
return user;
}
}).catch(function(err){
return err;
});

我将 Sequelize JS 与 Node JS 结合使用。我想要与 where 子句匹配的用户对象。但是当我从 then function 返回时。但它进入无限循环。我是 Node Js 的新手,不知道如何在 Node Js 中使用 Promise。请帮助我

最佳答案

db.User.find()的返回值是一个 promise 。它永远不会是用户,因此您的第一行不正确。

您需要做的是从 Promise then 中调用处理链中的下一个函数。打回来。这是 Node 中的标准做法。

如果您从then返回一些东西Promise 回调它被假定为另一个 Promise,它允许您连续链接多个 Promise( example )。这不是您要找的。

你的例子会更好,比如:

function authentication(err, user){
// Do something
}

db.User.find({ where: { username: username }}).then(function(user) {
console.log("Authenticate"+user.authenticate(password));
if (!user) {
authentication(null, null);
} else if (!user.authenticate(password)) {
authentication(null, null);
} else {
authentication(null, user);
}
}).catch(function(err){
authentication(null, user);
});

请注意使用回调来表示身份验证测试的结果。另请注意err作为回调的第一个参数,这是标准的 Node 约定。

关于javascript - 如何在 Sequelize Js 中使用 Promise 返回实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28472359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com