我编写了一个函数,可以通过 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 评级。 这是我在控制台上得到的输出。
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
8.1
7.3
8.1 和 7.3 是 getDeatils() 中控制台语句的值,这就是我返回的值。 当调用 movieDetails() 时,会打印 Promise 对象。 谁能指出我在这里做错了什么?
最佳答案
getDetails
函数返回订阅
,在movieDetails
中,您正在等待
这些订阅。简而言之,它不起作用。
当您订阅创建的可观察对象时,您将获得订阅来控制其生命周期。这些订阅不会对可观察值执行任何操作。
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
中提供的函数)。如果您应该使用等待,请将 Observables 转换为 toPromise
并仅获取最新数字 - 否则,只需在 getDetail
中返回 observable,然后通过观察者访问值即可。
关于javascript - 来自 observable 的 Promise 不会等待被实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754303/