我想通过提取一些函数来重构 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);
});
});
};
所以我想提取我解决
不成功响应的部分。但传递任何成功的。我是这样拔出来的。
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)
并且必须将 response
和 resolve
传递给它们中的每一个似乎是错误的
最佳答案
您还应该从外部函数返回一个新的 Promise:
const resolveUnsuccessfulResponses = (response) => {
return new Promise((resolve, reject) => {
if (!response.ok) {
return resolve(false);
}
return resolve(response);
});
}
关于javascript - 在 Promise 链中提取函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998617/