0

I have to use a method that returns a promise and that is inside a function. I want to return a value for the parent function in the .then() of the promise.

returnSomething():boolean{
  theFunctionThatReturnsAPromise()
    .then(
      //return true for the returnSomething function here
    ).catch(
      //return false for the returnSomething function here
    );
}

How can I do this with typescript/Javascript?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0

You can use async/await for this.

async function foo() {
    try {
        var val = await theFunctionThatReturnsAPromise();
        console.log(val);
    }
    catch(err) {
        console.log('Error: ', err.message);
    }
}

But the return value is still going to be a Promise, since it is asynchronous.

For a better understanding you might want to read this tutorial.

lumio
  • 7,428
  • 4
  • 40
  • 56
0

You can't return something directly because the thing you want to return isn't immediately available. That's the whole reason we use asynchronous things like promises. It's hard to know exactly what you are doing from a couple lines of code, but in general you just want to return the promise and allow the caller of the function to deal with it.

For example:

returnSomething():Promise<boolean>{
   return theFunctionThatReturnsAPromise()
}

Then the caller can deal with the value like:

returnSomething()
   .then(result => {
       if (result) { //etc.}
    }
   .catch( err => { console.log("an error happened", err)}
Mark
  • 90,562
  • 7
  • 108
  • 148