Bastien
Bastien

Reputation: 111

How do I check whether a function which uses a promise was successful?

I have these two functions. What I want when I call foo, then check whether it succeeded. So currently I'm doing something as suggested in this answer: Returning a value from a function depending on whether a Promise was resolved or not

function foo() {
  performOp()
    .then(() => {
      console.log('it worked!');
      return true;
    })
    .catch(err => {
      console.log('it failed!');
      return false;
    });
}

function bar() {
  foo().then(val => console.log(val));
}

The thinking here is that foo will return a promise to bar, and bar will print the result. Instead, what I'm seeing is that the return value of foo() is undefined.

Upvotes: 0

Views: 754

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

I think because you are not returning anything, otherwise the function returns undefined by default. Given that performOp is a promise it will be:

function foo() {
  return performOp()
    .then(() => {
      console.log('it worked!');
      return true;
    })
    .catch(err => {
      console.log('it failed!');
      return false;
    });
}

Upvotes: 3

Related Questions