Solo
Solo

Reputation: 6957

Rejecting Promise if many error sources

Im in situation where I have many potential error sources. Is there an elegant solution to this mess?

How should I reject it?

  function myFuction(hash) {
    return new Promise((resolve, reject) => {
      // this could return error
      const id = atob(hash);

      // this could return error   
      let data = firstFunction(id);

      // return error if not true
      if (data && data.id) {
        // this could return error   
        return secondFunction(data.id)
          .then(item => {

            // return error if not true
            if (item) {
              // this could return error  
              return thirdFunction(item)
                .then(payload => {
                  resolve('OK');
                });
            }
          });
      }
    });
  }

Upvotes: 0

Views: 38

Answers (1)

Bergi
Bergi

Reputation: 664237

Avoid the Promise constructor antipattern! You can use early returns with Promise.reject or just throw errors:

function myFuction(hash) {
    return Promise.resolve().then(() => {
        // this could throw error
        const id = atob(hash);
        // this could throw error   
        let data = firstFunction(id);

        // return error if not true
        if (!data || !data.id)
            return Promise.reject(new Error("…")); // alternative: throw new Error("…");

        return secondFunction(data.id);
    }).then(item => {
        // return error if not true
        if (!item)
            return Promise.reject(new Error("…")); // same here

        return thirdFunction(item);
    }).then(payload => 'OK');
}

(Additionally I applied some flattening, but as long as your always return from promise callbacks you could nest as well)

Upvotes: 2

Related Questions