Cleaner way to catch an error in a chain of nested promises?

Viewed 3502

I'm new to working with promises and am noticing that, in order to catch an error in a chain of nested promises, I need to invoke the catch method on each promise in the chain. Is there a cleaner way to write this?

      poll.pollForCandidates().then((candidates) => {
        let clientId = candidates[0].clientId;
        poll.getUnprocessedCandidates({context, clientId, candidates})
          .then((unprocessedCandidates) => {
            console.log(unprocessedCandidates);
            poll.addCandidatesToQueue(context, unprocessedCandidates)
              .then((processedCandidates) => {
                console.log(processedCandidates);
                poll.addCandidatesToTable(processedCandidates)
                  .then((result) => {
                    console.log(result);
                  })
                  .catch((error) => {
                    console.log(error);
                  });
              })
              .catch((error) => {
                console.log(error); 
              })
          })
          .catch((error) => {
             console.log(error); 
          })
      })
      .catch(() => {
        console.done(error); 
      });
    };
2 Answers
Related