rxjs5 toPromise not working

时间:2017-04-10 01:32:32

标签: javascript rxjs5

In the following example toPromise does not work:

https://jsfiddle.net/tossp/nmf9jg32/

My code:

function getPostData() {
    return fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(res => res.json())
}
var source = Rx.Observable.fromEvent(document.body, 'click');

var example = source.concatMap(
            e => Rx.Observable.from(getPostData()), 
            (e, res, eIndex, resIndex) => res.title);

example.subscribe({
    next: (value) => { console.log('subscribe!!!',value); },
    error: (err) => { console.log('Error: ' + err); },
    complete: () => { console.log('complete'); }
});
example.do((value)=>console.log('do!!!',value)).toPromise().then((value)=>console.log('toPromise!!!',value));

2 个答案:

答案 0 :(得分:1)

在较新的版本中,您必须在static void Main() { using (var cts = new CancellationTokenSource()) { // Start the worker thread and pass the // CancellationToken to it Console.WriteLine("MAIN: Starting worker thread"); var worker = Task.Run(() => dssPut_Command(cts.Token)); // Make the token cancel automatically after 3 seconds cts.CancelAfter(3000); // Wait for worker thread to exit Console.WriteLine("MAIN: Waiting for the worker to exit"); worker.Wait(); Console.WriteLine("MAIN: Main thread exiting after worker exited"); } } static void dssPut_Command(object tokenObj) { Console.WriteLine("WORKER: Worker thread started"); var cancellationToken = (CancellationToken)tokenObj; // You can check if cancellation has been requested if (cancellationToken.IsCancellationRequested) { // If there's no need to clean up, you can just return return; } try { // Or you can throw an OperationCanceledException automatically cancellationToken.ThrowIfCancellationRequested(); // Pass the CancellationToken to any methods you call // so they can throw OperationCanceledException when // the token is canceled. DoWork(cancellationToken); } catch (OperationCanceledException) { // Do any clean-up work, if necessary Console.WriteLine("WORKER: Worker exiting gracefully"); } } static void DoWork(CancellationToken cancellationToken) { // Simulating a long running operation Task.Delay(TimeSpan.FromMinutes(1), cancellationToken).GetAwaiter().GetResult(); } 内使用take(1)。我做了这种代码:

pipe()

希望它可以帮助某人。

答案 1 :(得分:0)

已经解决了https://github.com/ReactiveX/rxjs/issues/2536

toPromise基本上是observable.last().subscribe()

如果您在致电.take(1)之前添加toPromise,那么事情就会开始奏效。

example.do((value)=>console.log('do!!!',value)).take(1).toPromise()