skip to Main Content

I have a piece of code in which multiple promises are being handled using Promise.all, but one of the promise isn’t resolving or rejecting but throwing error. Now my question is how to handle this error inside promise.all.

Please note, promises are coming from 3rd party module (node_modules) so i cannot change the code inside the promises, but can only handle the error.

a implementation of above question is

try {
  const a = await Promise.all([
    Promise.resolve(1),
    func1()
    // Promise.reject(4),
  ]);

  console.log(a);
} catch (e) {
  console.log("caught", e); // no error caught
}

// suppose func1 is some function exported by 3rd party package
async function func1() {
  return await new Promise((rs, rj) => {
    return setTimeout(() => {
      throw new Error("error");
    }, 1000);
  });
}

Tried many ways like

func1().catch(e => e)
func2(){
  try{ func1() }catch(err){ throw err }
}

2

Answers


  1. You should use reject callback in a promise constructor explicitly, otherwise your error is thrown in another JS macrotask, not affecting the promise.

    Given that an async function rejects a promise properly Promise.all works as expected:

    // suppose func1 is some function exported by 3rd party package
    function func1() {
      return new Promise((resolve, reject) => setTimeout(() => reject(new Error("my promise error")), 1000));
    }
    
    (async () => {
      
      try{
        await Promise.all([func1()]);
      }catch(e){
        console.log(e.message);
      }
    
    })();
    Login or Signup to reply.
  2. The code in the post launches a timeout that throws an error at global file level rather than in code that executes within a try/catch block the promise job handler puts aroundfulfilled, rejected, or finally handler code when executing them to see what they do and return.

    An error thrown at file level could be monitored by a window.onerror listener. You might be able to detect that and use it to reject a promise that could also be resolved by the problematic promise provider if it works. Then use a Promise.race construct to see which happens first – an error is thrown at file level, or the Promise.all becomes settled.

    This is not an ongoing fix – the approach is assuming the error is thrown by the dodgy promise provider, but not proven.

    As a code outline:

    const pAll = Promise.all( list of promises... );
    const pError = new Promise( (resolve, reject) => {
       window.addEventListener("error", reject);
    });
    const pResult = Promise.race( pAll, pError);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search