John C.
John C.

Reputation: 445

Handling async promises inside if statements

I am dealing with the following scenario in javascript. tt resembles a function from a package that return reject promise if something didn't happen. I want to Booleanize the await tt() in the test() function if that reject promise is triggered. the current setup results in catching the error and the else() block is not executed. is there a way to overcome that?

async function tt(){
  
  return Promise.reject('failed');
  
}


async function test(){
  
  if (somecondition && await tt()) //assume somecondition is true    
  {
    console.log("accept")
  }
  else
  {
    console.log("reject")
  }
    
}

test()
.catch(err=>console.log(err))

I want to avoid using .then(res ... ).catch(err ...)

Upvotes: 0

Views: 151

Answers (2)

AKX
AKX

Reputation: 169416

So you don't care about the resolved value or the rejection error? Sure:

async function tt() {
  return Promise.reject("failed");
}

function promiseAsBoolean(p) {
  return p.then((s) => true, (e) => false);
}

async function test() {
  if (somecondition && (await promiseAsBoolean(tt()))) {
    console.log("accept");
  } else {
    console.log("reject");
  }
}

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817238

You can tt in your own function that catches the error:

async function wrapped_tt() {
  try {
    await tt();
    return true; // or return await tt(); depending on what tt returns
  } catch {
    return false;
  }
}

later

if (somecondition && await wrapped_tt()) {

Of course you may want to check the error thrown by tt and only decide to return false for some of those errors.

Upvotes: 1

Related Questions