gpt4 book ai didi

javascript - 使用 flatMapLatest 处理错误并重试

转载 作者:行者123 更新时间:2023-11-29 19:25:49 25 4
gpt4 key购买 nike

我有一个网页,其中有一堆用户可以点击的项目。单击任何项​​目,取决于它的类型,将向服务器发送 ajax 请求,然后显示更多项目。如果请求导致错误,我想显示它,然后允许用户像以前一样继续单击或与页面交互。

我的代码是这样的

$scope.$createObservableFunction("clickHandler")
.flatMapLatest(function (args) {
//send the ajax request to the server
})
.retry()
.subscribe(function (data) {
//handle getting the data from the server
})

我究竟在哪里可以处理错误情况?我预计会发生错误,并且我一直想重新订阅源,但我希望有机会处理该错误。

最佳答案

诀窍是将错误转化为数据:

$scope.$createObservableFunction("clickHandler")
.flatMapLatest(function (args) {
//send the ajax request to the server
var ajaxQuery = someObservable;

// turn the observable into
// a stream of eithers, which will
// either have a 'result'
// or an 'error'
// use .catch() to turn the error
// into a either with an error property
// use .map() to turn the success
// into a either with the result property
return ajaxQuery
.map(function (result) {
return { result: result };
})
.catch(function (error) {
return Rx.Observable.of({ error: error });
});
})
.subscribe(function (data) {
if (data.error) {
// display data.error to user
}
else {
// display data.result to user
}
})

如果您的 ajax 方法返回一个 Promise,请使用 then 链接:

$scope.$createObservableFunction("clickHandler")
.flatMapLatest(function (args) {
//send the ajax request to the server
var ajaxQuery = somePromise;

// turn the promise into
// a promise of eithers, which will
// either have a 'result'
// or an 'error'
return ajaxQuery
.then(function onSuccess(result) {
return { result: result };
}, function onError (error) {
return { error: error };
});
})
.subscribe(function (data) {
if (data.error) {
// display data.error to user
}
else {
// display data.result to user
}
})

关于javascript - 使用 flatMapLatest 处理错误并重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30876829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com