简体   繁体   English

可观的承诺迫不及待地实现

[英]Promise from observable doesn't wait to be fulfilled

I have written a function that will get the IMDB ratings of an IMDB ID through an API. 我编写了一个函数,该函数将通过API获得IMDB ID的IMDB等级。 This is the function to which i pass the IMDB ID 这是我将IMDB ID传递给的功能

async function movieDetails(ID){
    let ratings= await getDetails(ID);
    return ratings;
}

And this is the function that returns the IMDB 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));
}

But this function is returning a promise object instead of IMDB rating. 但是此函数返回的是promise对象,而不是IMDB评级。 And this is the output which i get on the console. 这是我在控制台上得到的输出。

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} 承诺{[[[PromiseStatus]]:“待定”,[[PromiseValue]]:未定义}

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} 承诺{[[[PromiseStatus]]:“待定”,[[PromiseValue]]:未定义}

8.1 8.1

7.3 7.3

8.1 and 7.3 are the values from the console statement in getDeatils() which is what i am returning. 8.1和7.3是getDeatils()中控制台语句的值,这是我要返回的内容。 And the promise object are printed when movieDetails() is called. 并且在调用movieDetails()时将打印promise对象。 Can anyonebody point me out, what i am doing wrong here ? 谁能指出我在这里做错了什么?

getDetails function returns subscription , and in movieDetails you are await ing those subscription. getDetails函数返回subscription ,在movieDetails您正在await这些预订。 In short, it doesn't work. 简而言之,它不起作用。

When you subscribe into created observable you get subscription to control its lifecycle. 订阅创建的可观察对象时,您将获得订阅以控制其生命周期。 Those subscription doesn't do anything with values of observables. 这些订阅对可观察值没有任何作用。

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

Secondly, you can't directly await Observables - await keyword is for Promise. 其次,您不能直接await Observables-await关键字用于Promise。 In Observables, observer is way to access values (function supplied in subscribe ). 在Observables中,观察者是访问值的方式( subscribe提供的函数)。 If you should use await, convert Observables into toPromise and get only latest number - otherwise, just return observable in getDetail then access values via observer is way to go. 如果您应使用await,请将Observables转换为toPromise并仅获取最新数字-否则,只需在getDetail返回observable getDetail然后可以通过观察者访问值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM