Search code examples
promisesequelize.jsbluebird

Making concurrent call in Bluebird promise using Sequelize findOne method . Returns undefined


I want to verify existence of specific user data from multiple tables to make it a concurrent call i am using Bluebird Promise.Prop like given below. Data is acceded Using sequelize ORM.

Promise.props({
  user: (()=>{
    return User.findOne({
        where: {username: req.user.username}

    });
  }),
  comments: (()=>{
    return comments.findOne({
        where: {username: req.user.username}

    });
  })
}).then((result)=> {
    console.log(result.user.name, result.comments.count);
});

I also tried with a nested promise but doesn't succeeded. like

 Promise.props({
   user: (()=>{
    return User.findOne({
        where: {username: req.user.username}

    }).then((user)=>{
      console.log(user.name); // even here i am getting undefined
    });
  }),
  comments: (()=>{
    return comments.findOne({
        where: {username: req.user.username}

    });
  })
}).then((result)=> {
    console.log(result.user.name, result.comments.count);
});

Solution

  • You are not clear if result.user is undefined, or result.user.name is undefined. I expect the latter.

    You pass an object with 2 keys to Promise.props. But both of the keys are a function, and not a promise. So promise.props sees the function, not the promise. The result should still have the 2 functions.

    Try

    Promise.props({
      user: User.findOne({
            where: {username: req.user.username}
      }),
      comments: comments.findOne({
            where: {username: req.user.username}
      })
    }).then((result)=> {
        console.log(result.user.name, result.comments.count);
    });
    

    Other good ways are Promise.all, or if you know how many promises you have then use Promise.join

    Promise.join(
      User.findOne({
            where: {username: req.user.username}
      }),
      comments.findOne({
            where: {username: req.user.username}
      }),
      (user, comment) => {
        console.log(user.name, comments.count);
      }
    );