我处于有许多潜在错误源的情况下。有没有解决这个麻烦的优雅方法?

我应该如何拒绝它?

  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');
                });
            }
          });
      }
    });
  }

最佳答案

避免使用Promise constructor antipattern!您可以将早期回报与Promise.reject一起使用,或者仅将throw错误使用:

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');
}


(另外,我应用了一些flattening,但是只要您始终从promise回调中获取return,您也可以嵌套)

关于javascript - 如果错误源很多,则拒绝 promise ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43856681/

10-11 23:24
查看更多