在Promise链中提取函数

时间:2016-06-23 17:53:57

标签: javascript node.js ecmascript-6 es6-promise method-chaining

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

<p>

所以我想提取I 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); }); }); }; 。如何在外部函数中解析此Promise? 我应该将resolve is not defined传递给我提取的函数吗?那似乎很笨拙。

resolve

我可能最终会有像

这样的东西
.then(response => resolveUnsuccessfulResponses(response, resolve))

必须将.then(fetchres.json) .then(parseResponseData) .then(postDataSomewhere) .then(doOtherThings) .then(doEvenMoreCoolThings) response传递给他们每个人似乎都错了

1 个答案:

答案 0 :(得分:1)

您应该从外部函数返回一个新的Promise:

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