在 Promise 链中提取函数

Extracting functions in a Promise chain

我想通过提取一些函数来重构 Promise 链。目前我有

const getData = (uuid) => {
  return new Promise((resolve) => {
    fetch(
      // go fetch stuff
    )
    .then((response) => {
      if (!response.ok) {
        return resolve(false);
      }
      return response;
    })
    .then(fetchres.json)
    .then(response => {
      // Do more stuff that requires resolves that I will also want to refactor
    })
    .catch(err => {
      console.log(err);
      resolve(false);
    });
  });
};

所以我想提取 resolve 不成功响应的部分。但传递任何成功的。我是这样拔出来的。

const resolveUnsuccessfulResponses = (response) => {
  if (!response.ok) {
    return response.resolve(false);
  }
  return response;
}


const getData = (uuid) => {
  return new Promise((resolve) => {
    fetch(
      // go fetch stuff
    )
    .then(resolveUnsuccessfulResponses)
    .then(fetchres.json)
    .then(response => {
      // Do more stuff that requires resolves that I will also want to refactor
    })
    .catch(err => {
      console.log(err);
      resolve(false);
    });
  });
};

现在我收到错误 resolve is not defined 是可以理解的。如何在外部函数中解决此 Promise? 我应该将 resolve 传递给我提取的函数吗?这看起来很笨重。

.then(response => resolveUnsuccessfulResponses(response, resolve))

我最终可能会得到类似

的东西
.then(fetchres.json)
.then(parseResponseData)
.then(postDataSomewhere)
.then(doOtherThings)
.then(doEvenMoreCoolThings)

并且必须将 responseresolve 传递给他们每个人似乎是错误的

您还应该 return 来自外部函数的新 Promise:

const resolveUnsuccessfulResponses = (response) => {
  return new Promise((resolve, reject) => {
    if (!response.ok) {
      return resolve(false);
    }
    return resolve(response);
  });
}