简体   繁体   English

在 Observable 中使用 Promise

[英]Using Promise inside a Observable

Since inside a Observable we have an option of calling Promise ,I have a clarification regrading this.由于在 Observable 中,我们可以选择调用 Promise ,因此我对此进行了澄清。

Since a promise gets executed immediately after declaration , will it be executed without attaching Subscribe method to it ?由于承诺在声明后立即执行,是否会在不附加 Subscribe 方法的情况下执行? And also since it cannot be cancelled why would anyone think of calling a Promise inside a observable .而且既然它不能被取消,为什么有人会想到在 observable 中调用 Promise 。

Rx.Observable.fromPromise():

const computeFutureValue = new Promise((resolve, reject) => {
//make http api call
});

Rx.Observable.fromPromise(computeFutureValue)
.subscribe(
val => {
console.log(val);
},
err => {
console.log(`Error occurred: ${err}`);
},
() => {
console.log('All done!');
});

As you said, a Promises body is executed when you create the Promise.正如您所说,当您创建 Promise 时,会执行 Promises 主体。 So when you create this Promise:所以当你创建这个 Promise 时:

const computeFutureValue = new Promise((resolve, reject) => {
  //make http api call
});

the http request is executed no matter what you do next.无论您接下来做什么,都会执行 http 请求。 Using from (or fromPromise ) to convert the Promise to an Observable and subscribing to this Observable doesn't affect the Promise and it's execution in any way.使用from (或fromPromise )将 Promise 转换为 Observable 并订阅此 Observable 不会以任何方式影响 Promise 及其执行。

You'd want to convert a Promise to an Observable if you want to be able to work with all the operators Observables offer or because your app works with and requires Observables at certain points.如果您希望能够使用 Observables 提供的所有运算符,或者因为您的应用程序在某些点使用并需要 Observables,您可能希望将 Promise 转换为 Observable。

If you only want to create and execute a Promise when you subscribe to an Observable you can usedefer , see my answer here: Convert Promise to Observable如果您只想在订阅 Observable 时创建和执行 Promise,您可以使用defer ,请在此处查看我的答案: Convert Promise to Observable

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

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