RxJS序列相当于promise.then()?

时间:2015-12-30 05:17:53

标签: javascript rxjs

我过去经常发展很多,现在我转向RxJS。 RxJS的文档并没有提供一个关于如何从promise链到观察者序列的非常明确的例子。

例如,我通常用多个步骤编写promise链,比如

// a function that returns a promise
getPromise()
.then(function(result) {
   // do something
})
.then(function(result) {
   // do something
})
.then(function(result) {
   // do something
})
.catch(function(err) {
    // handle error
});

我应该如何以RxJS风格重写此承诺链?

8 个答案:

答案 0 :(得分:70)

对于数据流(相当于Rx.Observable.fromPromise(...) .flatMap(function(result) { // do something }) .flatMap(function(result) { // do something }) .subscribe(function onNext(result) { // end of chain }, function onError(error) { // process the error }); ):

RSVP.all

可以使用Rx.Observable.fromPromise将承诺转换为可观察对象。

有些承诺运营商有直接翻译。例如,jQuery.whenRx.Observable.forkJoin可以替换为retryWhen

请记住,您有一堆允许异步转换数据的运算符,以及执行您不能或者很难用promises执行的任务。 Rxjs使用异步数据序列(序列,即超过1个异步值)显示其所有权力。

对于错误管理,主题有点复杂。

  • 还有catchfinally运营商
  • onError也可以帮助在出错时重复序列
  • 您还可以使用Label Text Label TextArea 函数处理订阅者本身的错误。

要获得精确的语义,请深入了解您可以在网上找到的文档和示例,或在此处提出具体问题。

这绝对是使用Rxjs进行更深入错误管理的良好起点:https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/error_handling.html

答案 1 :(得分:20)

更现代的选择:

import {from as fromPromise} from 'rxjs';
import {catchError, flatMap} from 'rxjs/operators';

fromPromise(...).pipe(
   flatMap(result => {
       // do something
   }),
   flatMap(result => {
       // do something
   }),
   flatMap(result => {
       // do something
   }),
   catchError(error => {
       // handle error
   })
)

还要注意,要使所有这些工作正常进行,您需要subscribe到此管道Observable的某个地方,但是我认为它是在应用程序的其他部分中处理的。

答案 2 :(得分:1)

使用RxJs 6更新2019年5月

同意以上提供的答案,希望使用 RxJs v6 添加一些玩具数据和简单承诺(带有setTimeout)的具体示例,以增加清晰度。

只需将传递的ID(当前硬编码为1)更新为不存在的错误,即可执行错误处理逻辑。重要的是,还要注意将ofcatchError消息一起使用。

import { from as fromPromise, of } from "rxjs";
import { catchError, flatMap, tap } from "rxjs/operators";

const posts = [
  { title: "I love JavaScript", author: "Wes Bos", id: 1 },
  { title: "CSS!", author: "Chris Coyier", id: 2 },
  { title: "Dev tools tricks", author: "Addy Osmani", id: 3 }
];

const authors = [
  { name: "Wes Bos", twitter: "@wesbos", bio: "Canadian Developer" },
  {
    name: "Chris Coyier",
    twitter: "@chriscoyier",
    bio: "CSS Tricks and CodePen"
  },
  { name: "Addy Osmani", twitter: "@addyosmani", bio: "Googler" }
];

function getPostById(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const post = posts.find(post => post.id === id);
      if (post) {
        console.log("ok, post found!");
        resolve(post);
      } else {
        reject(Error("Post not found!"));
      }
    }, 200);
  });
}

function hydrateAuthor(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const authorDetails = authors.find(person => person.name === post.author);
      if (authorDetails) {
        post.author = authorDetails;
        console.log("ok, post hydrated with author info");
        resolve(post);
      } else {
        reject(Error("Author not Found!"));
      }
    }, 200);
  });
}

function dehydratePostTitle(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      delete post.title;
      console.log("ok, applied transformation to remove title");
      resolve(post);
    }, 200);
  });
}

// ok, here is how it looks regarding this question..
let source$ = fromPromise(getPostById(1)).pipe(
  flatMap(post => {
    return hydrateAuthor(post);
  }),
  flatMap(post => {
    return dehydratePostTitle(post);
  }),
  catchError(error => of(`Caught error: ${error}`))
);

source$.subscribe(console.log);

输出数据:

ok, post found!
ok, post hydrated with author info
ok, applied transformation to remove title
{ author:
   { name: 'Wes Bos',
     twitter: '@wesbos',
     bio: 'Canadian Developer' },
  id: 1 }

关键部分,等同于以下使用简单承诺控制流的内容:

getPostById(1)
  .then(post => {
    return hydrateAuthor(post);
  })
  .then(post => {
    return dehydratePostTitle(post);
  })
  .then(author => {
    console.log(author);
  })
  .catch(err => {
    console.error(err);
  });

答案 3 :(得分:0)

如果"pool-1-thread-3" #86 prio=5 os_prio=0 tid=0x00007f5490464800 nid=0x5f4b waiting on condition [0x00007f54434f3000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x0000000080135840> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039) at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1074) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) 函数位于流管道的中间,则应简单地将其包装到函数getPromisemergeMapswitchMap(通常为{{1} }):

concatMap

如果您想以mergeMap开始流,然后将其包装到stream$.pipe( mergeMap(data => getPromise(data)), filter(...), map(...) ).subscribe(...); 函数中:

getPromise()

答案 4 :(得分:0)

据我刚刚发现,如果您在flatMap中返回结果,即使您返回字符串,它也会将其转换为Array。

但是如果您返回一个Observable,则该observable可以返回一个字符串;

答案 5 :(得分:0)

如果我理解正确,则意味着要使用这些值,在这种情况下,请使用sbuscribe即。

arrObservable.toPromise().then()

此外,您可以使用toPromise()将可观察对象变成一个承诺,如下所示:

Host

答案 6 :(得分:0)

这就是我的方法。

以前

  public fetchContacts(onCompleteFn: (response: gapi.client.Response<gapi.client.people.ListConnectionsResponse>) => void) {
    const request = gapi.client.people.people.connections.list({
      resourceName: 'people/me',
      pageSize: 100,
      personFields: 'phoneNumbers,organizations,emailAddresses,names'
    }).then(response => {
      onCompleteFn(response as gapi.client.Response<gapi.client.people.ListConnectionsResponse>);
    });
  }

// caller:

  this.gapi.fetchContacts((rsp: gapi.client.Response<gapi.client.people.ListConnectionsResponse>) => {
      // handle rsp;
  });

之后(结束?)

public fetchContacts(): Observable<gapi.client.Response<gapi.client.people.ListConnectionsResponse>> {
    return from(
      new Promise((resolve, reject) => {
        gapi.client.people.people.connections.list({
          resourceName: 'people/me',
          pageSize: 100,
          personFields: 'phoneNumbers,organizations,emailAddresses,names'
        }).then(result => {
          resolve(result);
        });
      })
    ).pipe(map((result: gapi.client.Response<gapi.client.people.ListConnectionsResponse>) => {
      return result; //map is not really required if you not changing anything in the response. you can just return the from() and caller would subscribe to it.
    }));
  }

// caller

this.gapi.fetchContacts().subscribe(((rsp: gapi.client.Response<gapi.client.people.ListConnectionsResponse>) => {
  // handle rsp
}), (error) => {
  // handle error
});

答案 7 :(得分:0)

RxJS序列等同于promise.then()?

例如

function getdata1 (argument) {
        return this.http.get(url)
            .map((res: Response) => res.json());
    }

    function getdata2 (argument) {
        return this.http.get(url)
            .map((res: Response) => res.json());
    }

    getdata1.subscribe((data1: any) => {
        console.log("got data one. get data 2 now");
        getdata2.subscribe((data2: any) => {
            console.log("got data one and two here");
        });
    });