gpt4 book ai didi

javascript - RxJS - 发生错误时可观察对象未完成

转载 作者:IT王子 更新时间:2023-10-29 03:09:26 25 4
gpt4 key购买 nike

当我从头开始创建一个可观察对象并出现观察者错误,然后完成时,永远不会调用订阅的完成部分。

var observer = Rx.Observable.create(function(observer){
observer.onError(new Error('no!'));
observer.onCompleted();
})

observer.subscribe(
function(x) { console.log('succeeded with ' + x ) },
function(x) { console.log('errored with ' + x ) },
function() { console.log('completed') }
)

输出是:

errored with Error: no!

我希望它是:

errored with Error: no!
completed

如果我更改代码以调用 onNext 而不是 onError,则可观察对象正确完成:

var observer = Rx.Observable.create(function(observer){
observer.onNext('Hi!');
observer.onCompleted();
})

observer.subscribe(
function(x) { console.log('succeeded with ' + x ) },
function(x) { console.log('errored with ' + x ) },
function() { console.log('completed') }
)

我得到了预期的输出:

succeeded with Hi! 
completed

为什么在发生错误时没有完成?

最佳答案

那是因为错误意味着完成,所以永远不会调用与 onCompleted 关联的回调。您可以在此处查看 Rxjs 可观察对象合约 (http://reactivex.io/documentation/contract.html):

An Observable may make zero or more OnNext notifications, each representing a single emitted item, and it may then follow those emission notifications by either an OnCompleted or an OnError notification, but not both. Upon issuing an OnCompleted or OnError notification, it may not thereafter issue any further notifications.`

对于错误管理,您可以查看: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/errors.md

关于javascript - RxJS - 发生错误时可观察对象未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33783967/

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