Search code examples
javascriptpromisebluebird

Trying to figure out bluebird way of doing promise flow


I'm trying to figure out the proper way to do promisification - and more specifically using bluebird. I've come up with some code that makes use of new Promises:

function createUser(data) {
  return new Promise((resolve, reject) => {

    User.createAsync(user)
        .then((doc) => {
            resolve(doc);
        })
        .catch((err) => {
            reject(err);
        });
  });
}

function create(data) {
   return new Promise((resolve, reject) => {

    User.findOneAsync({username: data.username})
        .then((user) => {
            if (user) {
                 resolve(`Username ${data.username} is already taken`);
            } else {
                createUser(data)
                    .then((user) => {
                        resolve(user);
                    })
            }
        })
        .catch((err) => {
            reject(err);
        });
   })
}

But I feel like I'm not getting much out of bluebird this way and after browsing through the documentation it seems like this is something of an anti-pattern that should be avoided. How would I go about making for example this flow more bluebird style or better promisified in general?


Solution

  • Adding onto SimpleJ's answer, you can do the following with async functions to get even better code readability:

    function createUser(data) {
      return User.createAsync(data);
    }
    
    // async functions!
    //                     destructuring!
    async function create({username}) {
      //                                   short literals!
      const user = await User.findOneAsync({username});
      if (user) { throw new Error(`Username ${username} is already taken`); }
      return createUser(data);
    }
    

    This gives you a very flat, almost synchronous looking code. Note the await before User.findOneAsync() for waiting on the Promise.

    The code above is equivalent to the other answer's. Async functions require node 7.6 or higher.