[英]Promise from observable doesn't wait to be fulfilled
我編寫了一個函數,該函數將通過API獲得IMDB ID的IMDB等級。 這是我將IMDB ID傳遞給的功能
async function movieDetails(ID){
let ratings= await getDetails(ID);
return ratings;
}
這是返回IMDB等級的函數。
const getDetails = val =>{
return Rx.Observable.fromPromise(fetch(`http://www.omdbapi.com/?i=${val}&plot=full&apikey=${APIKey}`)
.then(e => e.json())
.catch(err => console.log(err)))
.map(e => e.imdbRating)
.subscribe(x => {
console.log(x);
return x;
}, e => console.error(e));
}
但是此函數返回的是promise對象,而不是IMDB評級。 這是我在控制台上得到的輸出。
承諾{[[[PromiseStatus]]:“待定”,[[PromiseValue]]:未定義}
承諾{[[[PromiseStatus]]:“待定”,[[PromiseValue]]:未定義}
8.1
7.3
8.1和7.3是getDeatils()中控制台語句的值,這是我要返回的內容。 並且在調用movieDetails()時將打印promise對象。 誰能指出我在這里做錯了什么?
getDetails
函數返回subscription
,在movieDetails
您正在await
這些預訂。 簡而言之,它不起作用。
訂閱創建的可觀察對象時,您將獲得訂閱以控制其生命周期。 這些訂閱對可觀察值沒有任何作用。
const obs = Observable.from(...) //obs is Observable
const subs = obs.subscribe((x) => console.log(x)); //subs is Subscription
// subs.unsubscribe(); //when you want to unsubscribe even source does not completes
其次,您不能直接await
Observables-await關鍵字用於Promise。 在Observables中,觀察者是訪問值的方式( subscribe
提供的函數)。 如果您應使用await,請將Observables轉換為toPromise
並僅獲取最新數字-否則,只需在getDetail
返回observable getDetail
然后可以通過觀察者訪問值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.