Auro
Auro

Reputation: 1628

Bluebird's Promise resolve returns undefined

I'm new to Promise, so I was trying out Bluebird's Promise APIs. I have the following method that returns a Promise.try()

CheckDb - Promise Method

const Prom = require("bluebird")

..........
..........

let checkDb = () => {
 return Prom.try(() => {
   SomePromiseMethod().then(result => {
    if (//some condition) {
      let resp = { 
          res: result, 
          somethingelse : somethingelse 
      }
      return Prom.resolve(resp)
    }
    else 
      return Prom.reject(new Error("some reason"));
   }, err => {
      return Prom.reject(err);
   })
   .catch(err => {
     return Prom.reject(err);
   });
 });
}

SomeTask - Method calling the promise method

exports.someTask = () => {
      checkDb().then(resolved => {
       console.log(resolved) // coming undefined
      }, 
      rejected => {
       console.error(rejected);
      })
      .catch(err => {console.error(err)});
    }

The problem here is that the resolved component of the then method of the Promise function is returning undefined.

I looked into this and this, but couldn't figure it out.

Upvotes: 0

Views: 199

Answers (1)

Rafael L. Toscano
Rafael L. Toscano

Reputation: 21

Try to return the value directly without using this Prom.resolve, like this:

...
        return SomePromiseMethod().then(result => {
            if (//some condition) {
              let resp = { 
                  res: result, 
                  somethingelse : somethingelse 
              }
              return resp
            }
            else 
              throw new Error("some reason"));
           }
    ...

If you are in the "then" method of a promise, you resolve it by returning a value, which is passed to the next "then" method in the chain.

You would use the resolve method explicitly if you had:

  • a defer created "by hand" and you wanted to resolve it
  • a promise created by you if you wanted to "promisify" something that is not a promise, like this example below:

    return new Promise(function(resolve, reject) { ... resolve(value);

    })

Which is not your case. (Edited this part of the answer to avoid misinterpretation)

Upvotes: 1

Related Questions