在Promise链中提取函数

我想通过提取出一些function来重构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错误resolve is not defined 。 我怎样才能解决这个承诺在外部function? 我应该通过resolve我的提取function? 这看起来笨重。

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

我可能会得到类似的东西

 .then(fetchres.json) .then(parseResponseData) .then(postDataSomewhere) .then(doOtherThings) .then(doEvenMoreCoolThings) 

而必须通过responseresolve他们每个人似乎是错误的

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

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