promise - Sequelize 检查行是否存在,并返回 bool 值

标签 promise sequelize.js

我正在尝试使用 Sequelize 查询关联表以查看一个用户是否正在关注另一个用户。如果关系存在,我想返回true。如果不是,则返回 false。我想将此响应返回到 toProfileJSONFor 的“以下”部分(见下文)。

基于日志记录,一切似乎都按预期工作,除了我收到一个 promise 而不是我的 bool 值。我已经阅读了尽可能多的关于 promise 的内容,但似乎仍然无法弄清楚我的问题。

这是我目前收到的结果:


{
    "profile": {
        "username": "superman1",
        "bio": null,
        "image": "",
        "following": {
            "isFulfilled": false,
            "isRejected": false
        }
    }
}

我知道这是 Promise 的问题,但我无法找到解决方案。


User.prototype.toProfileJSONFor = function(user){
  return {
    username: this.username,
    bio: this.bio,
    image: this.image || 'genericImage.jpg',
    following: user.isFollowing(this.id) //this is where I am having issues
  };

User.prototype.isFollowing = function(id){
  let userId = this.id; // current userId
  let followId = id; //profile Id


  return FollowerFolloweds.findAll({
    where: { followedId: followId, followerId: userId},raw : true })
    .then(function(result) {
      if(result.length !=0){
        return true;
      }  {
        return false;
      }

    })
}


预期的结果是:
{
    "profile": {
        "username": "superman1",
        "bio": null,
        "image": "",
        "following": true 
    }
}

最佳答案

请尝试以下操作:

User.prototype.toProfileJSONFor = function(user){
  return user.isFollowing(this.id)
    .then((following) => {
        username: this.username,
        bio: this.bio,
        image: this.image || 'genericImage.jpg',
        following
    });
}

关于promise - Sequelize 检查行是否存在,并返回 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56158703/

相关文章:

javascript - jquery $.when.apply().done 未触发

javascript - promise : then vs then + catch

javascript - 跨 Sequelize 关联播种数据

node.js - SequelizeConnectionError : FATAL: remaining connection slots are reserved for non-replication superuser connections

mysql - Ssequelizejs、MySQL 和 Passportjs user.findOne 不是函数

javascript - 处理/捕获错误而不重复代码?

javascript - promise 返回 promise ?

javascript - Promise 中的Resolve 到底有什么作用?

mysql - Sequelize 属于很多禁用相同的ID

postgresql - Mongoose 的前 ('save' 的 Sequelize 等价物是什么?