Reputation: 152
I have a function that has an observable object and I need to return the value of the fetch that I use in this function. But I don't know why I can not return the result when I display the result it is totally fine but when I try to return it is empty.
I check a few similar problems but they were very complex and also they didn't match my case and also after trying one or two of them still the problem exists.
function getRandomQuote() {
const obs$ = Observable.create(async(observer) => {
const result = await fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content)
observer.next(result)
console.log(result)
})
return obs$.subscribe(x => { return x })
}
I tried to use return only inside the subscribe part but it doesn't work and in one of the similar cases they tried to return the outer part which I tried and still not work
I am new with observable and JavaScrip I just need to return this value and use it in another function. thank you
Upvotes: 0
Views: 504
Reputation: 11345
You should return Observable
other than Subscription
function getRandomQuote() {
return Observable.create(async(observer) => {
const result = await fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content)
observer.next(result)
})
}
//usage
getRandomQuote().subscribe(console.log)
Or there is defer()
and from()
operator which helps you convert promise to observable
getRandomQuote=()=>defer(()=>from(fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content))
//usage
getRandomQuote().subscribe(console.log)
Upvotes: 1