【发布时间】:2017-02-05 07:03:43
【问题描述】:
我正在开发一个使用 what-wg fetch 的应用程序。我们以这种方式定义了默认的 fetch 中间件和选项:
export function fetchMiddleware(response) {
return new Promise(resolve => {
resolve(checkStatus(response));
}).then(parseJSON);
}
export const fetchDefaults = {
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
我们以这种方式使用我们的默认中间件/获取选项:
fetch('/api/specific/route', fetchDefaults)
.then(fetchMiddleware)
.then(function(data) {
// ... Dispatch case-specific fetch outcome
dispatch(specificRouteResponseReceived(data));
});
我们希望为整个应用程序中的所有 fetch 用法添加一个通用的后备捕获,换句话说,如下所示:
export function fetchGenericCatch(function(error) {
showGenericErrorFlashMessage();
})
fetch('/en/api/user/me/preferences', fetchDefaults)
.then(fetchMiddleware)
.then(function(data) {
dispatch(userPreferencesReceived(data));
})
.catch(fetchGenericCatch);
大量代码重复。我们想要一个可以为我们做所有这些的实用函数/类,例如像这样工作的东西:
genericFetch('/api/specific/route') // bakes in fetchDefaults and fetchMiddleware and fetchGenericCatch
.then(function(data) {
dispatch(userPreferencesReceived(data));
}); // gets generic failure handler for free
genericFetch('/api/specific/route') // bakes in fetchDefaults and fetchMiddleware and fetchGenericCatch
.then(function(data) {
dispatch(userPreferencesReceived(data));
})
.catch(function(error) {
// ...
}); // short-circuits generic error handler with case-specific error handler
主要需要注意的是,通用 catch 必须链接在 特定案例的 thens / catches 之后。
关于如何使用 whatwg-fetch / ES6 Promises 实现这一点的任何提示?
相关:
有类似的帖子,但它们似乎没有解决运行默认捕获的需求毕竟非默认thens 和catches:
- How to create a Promise with default catch and then handlers
- Default behavior if no other functions chained to a promise
10 月 14 日编辑:
【问题讨论】:
-
我是否理解正确,因为您想自动添加
.catch侦听器,即使用户在您的函数返回后附加了.then/.catches ?这是不可能的 AFAIK。 -
不,我想添加一个默认承诺
catch它将处理任何未捕获的错误 --- 如果错误适用 --- 如果catch处理程序没有另外定义。
标签: javascript promise ecmascript-6 es6-promise