Home > Back-end >  How to fire single await/async based on a condition?
How to fire single await/async based on a condition?

Time:05-11

I have a NodeJS app and I have two async blocks that I am calling but the condition is that if the first block returns a value, I don't want to fire the second block. This is how my code looks:

//BLOCK 1
await canFunction1HandleID(id)
.then( () => {
  const result = await functionOne(id);
    if(!result){
      //throw error
    }

    return result;
})

//BLOCK 2
await canFunction2HandleID(id)
.then( () => {
  const result = await functionTwo(id);
    if(!result){
      //throw error
    }

    return result;
})

If the first block returns a value, I just want to return that value and not have the second block execute. But right now both blocks are executed, one after another. Any idea why and how can I achieve that I am trying to do here?

TIA.

CodePudding user response:

Just put the first value into a variable?

const result1 = await canFunction1HandleID(id)
    .then(() => {
        const result = await functionOne(id);
        if (!result) {
            //throw error
        }
        return result;
    });

if (!result1) {
    const result2 = await canFunction2HandleID(id)
        .then(() => {
            const result = await functionTwo(id);
            if (!result) {
                //throw error
            }
            return result;
        });
};

CodePudding user response:

If canFunction1HandleID and canFunction2HandleID are functions that return Promise<bool>, what about the following?

//BLOCK 1
if (await canFunction1HandleID(id)) {
  const result = await functionOne(id);

  if (!result) {
    //throw error
  }

  return result;
}

//BLOCK 2
if (await canFunction2HandleID(id)) {
  const result = await functionTwo(id);

  if (!result) {
    //throw error
  }

  return result; 
}

CodePudding user response:

If the first block returns a value, I just want to return that value and not have the second block execute.

Suppose what you expect is: if functionOne has valid return, use it; otherwise try functionTwo and throw error if no valid return neither.

The code to implement the logic can be simply like:

const result = await functionOne(id).catch(()=>{}) || await functionTwo(id).catch(()=>{});
if (!result) {
    // throw error
}

CodePudding user response:

You dont have to use .then while using await. Async/await is introduced to avoid .then promise calls. you can try this way.

const result1 = await canFunction1HandleID(); if(result1){ return result1; } const result2 = await canFunction2HandleID(); return result2;

  • Related