RxJS序列等效于promise.then()
RxJS sequence equivalent to promise.then()?
我曾经用promise开发过很多东西,现在我要转到RxJS了。RxJS的文档没有提供一个关于如何从承诺链转移到观察者序列的非常清晰的例子。
例如,我通常用多个步骤编写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风格重写这个承诺链?
对于数据流(相当于then
):
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
});
承诺可以用Rx.Observable.fromPromise
转化为可观测的。
一些promise运算符具有直接翻译。例如RSVP.all
或jQuery.when
可以被Rx.Observable.forkJoin
代替。
请记住,您有一组运算符,它们允许异步转换数据,并执行无法或很难通过promise完成的任务。Rxjs通过异步数据序列(即超过1个异步值的序列)展示了它的所有能力。
对于错误管理,这个主题稍微复杂一些。
- 还有catch和finally操作符
retryWhen
还可以帮助在出现错误时重复序列- 您还可以使用
onError
函数处理订阅者本身的错误
要获得精确的语义,请更深入地查看您可以在网上找到的文档和示例,或者在这里提出特定的问题。
这肯定是使用Rxjs深入错误管理的一个很好的起点:https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/error_handling.html
更现代的替代方案:
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
,但我认为它是在应用程序的其他部分中处理的。
2019年5月更新,使用RxJs 6
同意以上提供的答案,希望添加一个具体的玩具数据示例;使用RxJs v6添加清晰度的简单承诺(带setTimeout)。
只需将传递的id(当前硬编码为1
)更新为不存在的id即可执行错误处理逻辑。重要的是,还要注意of
与catchError
消息的使用。
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);
});
如果我理解正确,你的意思是消费价值,在这种情况下,你使用sbusribe,即
const arrObservable = from([1,2,3,4,5,6,7,8]);
arrObservable.subscribe(number => console.log(num) );
此外,您可以使用toPromise()将可观察到的转化为promise,如图所示:
arrObservable.toPromise().then()
如果getPromise
函数位于流管道的中间,则应将其简单地包装为函数mergeMap
、switchMap
或concatMap
(通常为mergeMap
)之一:
stream$.pipe(
mergeMap(data => getPromise(data)),
filter(...),
map(...)
).subscribe(...);
如果你想用getPromise()
启动你的流,那么把它包装成from
函数:
import {from} from 'rxjs';
from(getPromise()).pipe(
filter(...)
map(...)
).subscribe(...);
据我所知,如果您在flatMap中返回结果,它会将其转换为Array,即使您返回字符串也是如此。
但是如果你返回一个Observable,那个Observable可以返回一个字符串;
我就是这么做的。
以前
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;
});
之后(ly?)
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
});
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");
});
});
- 将数据从promise then方法传递到对象方法
- JavaScript Promise then() ordering
- 使用promise.then时,是否可以保留在单击事件调用堆栈中
- 如何重写这段代码,使执行不必从Javascript Promise.then()方法开始
- ngResource.myfunc().$promise.then 返回空数组
- 量角器:我是否过度使用了promise.then()
- 为什么来自 Promise '.then' 方法的回调是反模式
- RxJS序列等效于promise.then()
- Promise : then vs then + catch
- 如何从promise .then handler触发.fail处理器
- 当promise.then中的expect失败时,Protractor / cucumber测试套件停止运行
- Promise.then()但函数异步运行
- 装饰 Javascript Promise.then 以便参数函数接收附加参数
- Javascript: Promise() .then不起作用
- 测试没有运行service mock promise (.then)
- 当我需要调用者的执行暂停/等待时,如何使用promise.then() ?
- 如何在任意数量的链元素上使用map或reduce来运行promise-then链
- 将对象绑定到Promise.then()参数的正确方法
- 在promise.then()中设置模型时,视图中的Nativescript绑定属性不会更新
- ng-change在promise.then中未调用we-ng模型更新