问题
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;
}
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();
}
回答1:
Passing an async
function to subscribe
is pointless - it throws away the returned promise, it doesn't wait for anything. You would need to use
new Promise((resolve, reject) => {
someService.someObservable.subscribe(resolve, reject);
})
or just call the builtin toPromise method:
async function helpMe() {
await someService.someObservable.toPromise();
return getDataFromApi();
}
回答2:
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();
}
来源:https://stackoverflow.com/questions/56834905/return-promise-value-from-observable-subsciption