从可观察的订阅中返回承诺值 [英] Return promise value from observable subsciption
本文介绍了从可观察的订阅中返回承诺值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有机会从getDataFromApi()的helpMe函数值返回?到目前为止,每次我调用此函数时,我都会得到"null"值.
Is there any chance to return from helpMe function value from getDataFromApi() ? So far every time i call this function i get "null" value.
async function helpMe() {
let promise = null;
let sub = someService.someObservable.subscribe(async () => {
promise = await getDataFromApi()
})
subscriptions.push(sub)
return promise;
}
第一个目标是我需要将预订存储在全局子数组中.第二个目标是当我收到状态为400的响应时-我不想打开模式.只有当我得到200并且一切都很好时,我才希望打开模式.
The first goal is i need to store subscription in global sub array. The second goal is when i get response with status 400 - I dont want to open modal. Only when i get 200 and everything is allright i want modal to be opened.
function async load() {
const promise = await helpMe();
openModal();
}
推荐答案
您可以只使用普通的rxjs
而不是使用异步/等待功能. switchmap
运算符可能在这里为您提供帮助:
Instead of using async/await feature, you could just go with plain rxjs
. The switchmap
operator might help you here:
public helpMe()
{
return this.someService.someObservable.pipe(
switchMap(result =>
{
return someDataFromApi();
}),
tap(resultFromApi => {
// ... do something with `resultFromApi` from `someDataFromApi`.
}),
).toPromise();
}
这篇关于从可观察的订阅中返回承诺值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文