0

Can someone suggest to me how i can replicate this code with proper error handling without using await ? I would like to run fnA/B/C asynchronously rather than sequentially with await, i would also like to handle all rejections to be handled in the main catch block.

Thanks

async function() {
  try {
    let a = await fnA();
    let b = await fnB();
    let c = await fnC();
    return(a+b+c);
  }
  catch(e) {
    e.exitCode === 'fnAError' ? doSomething : null;
    e.exitCode === 'fnBError' ? doSomething : null;
  }
}

After all the suggestions this is what i ended up with:

const caller = async () => {
  try {
    let promisePool = [];
    let a = await testA();
    let b = promisePool.push(testB()) - 1;
    let c = promisePool.push(testC()) - 1;

    let q = await Promise.all(promisePool);
    // Get all the non awaited values
    console.log(q[b]);
  }
  catch(e) {
    console.log('caller catch');
    console.log('ERROR: ' + e);
  }
}

Thanks everyone

1
  • Thanks everyone, looks like await Promise.all is what i was looking for! Commented Apr 24, 2020 at 18:17

2 Answers 2

2

You have an AB problem.

If you want them to run in parallel instead of in series then the solution isn't to not use await, it is to use Promise.all.

try {
    let [a, b, c] = await Promise.all([fnA(), fnB(), fnc()]);
    return a + b + c;
}

You just need to await all the promises instead of each one in turn.

Sign up to request clarification or add additional context in comments.

1 Comment

You might also show how this could be done without await since it isn't really necessary to a simple solution either.
0

You can either combine await with Promise.all() like this:

async function() {
  try {
    const [a,b,c] = await Promise.all([fnA(), fnB(), fnC()]);
    return(a + b + c);
  }
  catch(e) {
    e.exitCode === 'fnAError' ? doSomething : null;
    e.exitCode === 'fnBError' ? doSomething : null;
    throw e;
  }
}

Or, you can use .then() and .catch() instead:

async function() {
    return Promise.all([fnA(), fnB(), fnC()]).then(([a, b, c]) => {
        return a + b + c;
    }).catch(err => {
        e.exitCode === 'fnAError' ? doSomething : null;
        e.exitCode === 'fnBError' ? doSomething : null;
        throw e;
    });
}

Note, if you're trying to return the modified error object to the caller of this function (still as a rejection), you need to rethrow the error after modifying it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.