Observables简介以及它们与Promise有何不同

news/2024/7/7 19:41:39

Observables’, ‘Observables’, ‘Observables’...Yes! Today, we will talk about this often discussed word of the market. We'll also learn how they are different from Promises (haven't heard about Promises? Not to worry! You will know more soon). Let’s start!

可观察物 ”,“ 可观察物 ”,“ 可观察物 ” ...是的! 今天,我们将讨论这个经常讨论的市场词汇。 我们还将学习它们与Promises有何不同(还没有听说过Promises吗?不用担心!您很快就会知道的)。 开始吧!

I first encountered the term Observable when I started learning Angular. Although it’s not an Angular-specific feature, it’s a new way of handling async requests.  Async request?  You know it, right? No! It’s ok. Let’s first understand what’s an async request is then.

当我开始学习Angular时,我首先遇到了Observable一词。 尽管它不是特定于Angular的功能,但它是一种新的处理方式 异步的 要求。 异步请求? 你知道吧? 没有! 没关系。 首先让我们了解什么是异步请求。

异步请求 (Async Requests)

Well! You must have read about asynchronous features in the JavaScript world. 'Asynchrony' in the computer world means that the flow of the program occurs independently. It does not wait for a task to get finished. It moves to the next task.

好! 您必须已了解JavaScript世界中的异步功能。 在计算机世界中,“ 异步 ”意味着程序流是独立发生的。 它不等待任务完成。 它移至下一个任务。

Now, you might be thinking - what happens to the task that is not finished? The co-worker handles those unfinished tasks. Yes! In the background, a co-worker works and handles those unfinished tasks and once they are done, it sends data back.

现在,您可能在想-未完成的任务会发生什么? 同事处理那些未完成的任务。 是! 在后台,一位同事工作并处理那些未完成的任务,一旦完成,便将数据发送回去。

This can bring up another question of how we handle the data that is returned. The answer is Promises, Observables, callbacks and many more.

这可能会引起另一个问题,即我们如何处理返回的数据。 答案是PromisesObservablescallbacks等等。

We know that these asynchronous operations return responses, either some data after success or an error. To handle this, concepts like Promises, callbacks, observables came into the market. Well! I will not get into them now as we have deviated from our sub topic i.e 'async' request. (Don't worry! These topics will be discussed soon).

我们知道这些异步操作返回响应,无论是成功后的一些数据还是错误。 为了解决这个问题,诸如Promisescallbacksobservables之类的概念进入了市场。 好! 现在,由于我们已经偏离了子主题(即“ 异步 ”请求),因此现在不再赘述 。 (不用担心!这些主题将很快讨论)。

After discussing the above points, you might ha have got a rough picture of what the async request is. Let’s clear it up. An Async request is one where the client does not wait for the response. Nothing is blocked. Let’s understand this concept by looking at a very common scenario.

在讨论了以上几点之后,您可能已经大致了解了异步请求是什么。 让我们清除它。 异步请求是客户端不等待响应的请求。 没有任何障碍。 让我们通过看一个非常普通的场景来理解这个概念。

In the web world, it's quite common to hit the server to get data like the details of a user, a list, and so on. We know it will take time and anything can follow (success/failure).

在网络世界中,击中服务器以获取诸如用户详细信息,列表等之类的数据是很普遍的。 我们知道这将需要时间,并且一切都会随之而来(成功/失败)。

this case, instead of waiting for data to come, we handle it asynchronously (no waiting) so that our application does not get blocked. Such requests are asynchronous requests. I think now we are clear with it. So let's see how we can actually handle these async requests.

在这种情况下,我们不是等待数据到来,而是异步处理(不等待),以便我们的应用程序不会被阻塞。 这样的请求是异步请求。 我认为现在我们很清楚了。 因此,让我们看一下如何实际处理这些异步请求。

As I already told you, Observables gave us a new way of handling async requests. The other ways are promises, callbacks, and async/await. These are the popular ways. Let’s have a look at two of them which are callbacks and promises.

正如我已经告诉您的那样,Observables为我们提供了一种处理异步请求的新方法。 其他方式是承诺,回调和异步/等待。 这些是流行的方式。 让我们看一下其中的两个是回调和承诺。

回呼 (Callbacks)

Callbacks are quite a common one. Callback functions (as their name suggests) are called at the back. That is when the request gets completed and returns the data or error, these functions get called. Have a look at the code for a better understanding:

回调是很常见的一种。 回调函数(顾名思义)在后面被调用。 也就是说,当请求完成并返回数据或错误时,将调用这些函数。 看一下代码以获得更好的理解:

const request = require(‘request’);
request('https://www.example.com', function (err, response, body) {if(error){// Error handling}else {// Success }
});

This is one way of handling an async request. But what happens when we want to again request to the server for data after the success of the first request? What if we want to make a third request after that successful second request? Horrible!

这是处理异步请求的一种方法。 但是,当我们希望在第一个请求成功后再次向服务器请求数据时,会发生什么情况? 如果我们想在第二次成功请求后再次提出第三次请求怎么办? 可怕!

At this point, our code will become messy and less readable. This is called ‘callback hell’. To overcome it, promises came around. They offer a better way of handling an async request that improves code readability. Let’s understand a bit more.

在这一点上,我们的代码将变得凌乱且可读性差。 这称为“ 回调 地狱 ”。 为了克服它,诺言应运而生。 它们提供了一种更好的方式来处理异步请求,从而提高了代码的可读性。 让我们了解更多。

承诺 (Promises)

Promises are objects that promise they will have value in the near future - either a success or failure. Promises have their own methods which are then and catch. .then() is called when success comes, else the catch() method calls.  Promises are created using the promise constructor. Have a look at code to better understand.

承诺是承诺它们将在不久的将来获得价值的对象-成功或失败。 承诺有自己的方法, 然后 赶上 。 成功时将调用.then() ,否则将调用catch()方法。 承诺 是使用promise构造函数创建的。 查看代码以更好地理解。

function myAsyncFunction(name){return new Promise(function(resolve, reject){if(name == ‘Anchal’){resolve(‘Here is Anchal’)}else{reject(‘Oops! This is not Anchal’)}}
} myAsyncFunction(‘Anchal’)
.then(function(val){// Logic after successconsole.log(val)     // output -  ‘Here is Anchal’
})
.catch(function(val){//Logic after failureconsole.log(val)     // output - ‘Oops! This is not Anchal’
})

As you can see, myAsyncFunction is actually promising that it will have some value in near future. .then() or .catch() is called according to the promise's status.

如您所见, myAsyncFunction实际上承诺在不久的将来会有所价值。 .then ().catch()根据诺言的状态被调用。

Promises improve code readability. You can see how readable the code is by using promises. Better handling of async operations can be achieved using Promises. This is a brief introduction of what promises are, how they handle data and what beauty promises carry.

承诺提高代码的 可读性 。 您可以通过使用promise来查看代码的可读性。 使用Promises可以更好地处理异步操作。 这是关于什么是承诺,它们如何处理数据以及美好承诺所承载的内容的简要介绍。

Now, it's time to learn about our main topic: Observables.

现在,是时候了解我们的主要主题:可观测值。

什么是可观测值? (What are Observables?)

Observables are also like callbacks and promises - that are responsible for handling async requests. Observables are a part of the RXJS library. This library introduced Observables.

可观察对象还类似于回调和承诺-负责处理异步请求。 可观察对象是RXJS库的一部分。 该库介绍了Observables。

Before understanding what an observable actually is, you must understand two communication models: pull and push. These two concepts are protocols of how producers of data communicate with the consumers of data.

在了解实际可观察​​的内容之前,您必须了解两种通信模型: pullpush 。 这两个概念是数据生产者如何与数据消费者进行通信的协议。

推拉模型 (Pull & Push Model)

As I have already told you, Push and Pull are communication protocols between data producers and consumers.  Let’s understand both one by one.

正如我已经告诉您的,推入和拉出是数据生产者和使用者之间的通信协议。 让我们一一理解。

Pull Model: In this model, the consumer of data is king. This means that the consumer of data determines when it wants data from the producer. The producer does not decide when the data will get delivered. You can better understand if you relate functions to it.

拉模型:在此模型中,数据的使用者 。 这意味着数据的使用者确定何时从生产者那里获取数据。 生产者不决定何时发送数据。 您可以更好地了解是否将功能与其相关联。

As we know, functions are responsible for doing some task. For example, dataProducer is a function which is simply returning a string, like "Hi Observable".

众所周知,函数负责完成某些任务。 例如, dataProducer是一个仅返回字符串的函数,例如“ Hi Observable ”。

function dataProducer(){return ‘Hi Observable’;
}

Now, you can see that the above function is not going to decide when it will deliver the ‘Hi Observable’ string. It will decide by the consumer, that is code that calls this function. Consumer is king. The reason why it is called a pull model is that pull task is determining the communication.  This is the pull Model. Now, let’s go into the Push Model.

现在,您可以看到上面的函数不会决定何时传递“ Hi Observable”字符串。 它将由使用者决定,即调用此函数的代码。 消费者为王。 之所以称为拉模型,是因为任务决定了通信。 这是 模型 。 现在,让我们进入Push 模型

Push Model: In this model, the producer of data is king. Producer determines when to send data to consumer. The Consumer does not know when data is going to come. Let’s understand it by taking an example:

推模式:在这种模式下,数据的生产者 。 生产者确定何时将数据发送给消费者。 消费者不知道何时将要收到数据。 让我们通过一个例子来理解它:

I hope you remember promises. Yes, Promises follow the push model.  A Promise (producer) delivers data to the callback (.then() - consumer). Callbacks do not know when data is going to come. Here, promise (producer) is king. It is determining the communication. That’s why it's called Push Model as the producer is in charge.

我希望你记得诺言 是的, Promise遵循 模型 Promise(生产者)将数据传递给回调( .then() -消费者)。 回调不知道数据何时到达。 在这里, 诺言 (生产者)为王。 它正在确定通信。 这就是为什么将其称为“ 模型”,因为生产者负责的原因。

Like promises, Observables also follow the push model. How? You will get the answer once I elaborate on observables. Let’s get back to observables then.

像诺言一样,Observables也遵循推模型。 怎么样? 一旦我详细介绍了可观察性,您就会得到答案。 然后让我们回到可观察的事物。

可观察的功能 (Observables as functions)

To simply understand, you can think of observables as functions. Let’s have a look at the below examples:

为了简单理解,您可以将可观察对象视为函数。 让我们看下面的例子:

function dataProducer(){return ‘Hi Observable’
}var result = dataProducer();
console.log(result) // output -  ‘Hi Observable’

You can get the same behaviour using an observable:

您可以使用可观察到的行为获得相同的行为:

var observable = Rx.Observable.create((observer: any) =>{observer.next(‘Hi Observable’);})observable.subscribe((data)=>{console.log(data);    // output - ‘Hi Observable’
})

From above, you can see both functions and observables show the same behaviour. This may bring a question to your mind - are observables the same as functions? No. I'll clarify in a minute why the answer is no. Have a look at an elaborate version of the above example.

从上面可以看到,函数和可观察对象都显示相同的行为。 这可能会给您带来一个问题-可观察对象是否与函数相同? 不,我将在稍后说明为什么答案是否定的。 看一下上面示例的详细版本。

function dataProducer(){return ‘Hi Observable’;return ‘Am I understandable?’ // not a executable code.
}var observable = Rx.Observable.create((observer: any) =>{observer.next(‘Hi Observable’);observer.next( ‘Am I understandable?’ );})observable.subscribe((data)=>{console.log(data);    
})Output :
‘Hi Observable’
‘Am I understandable?’

I hope you can now see what difference I wanted to address. From above, you can see, both functions and observables are lazy. We need to call (functions) or subscribe (observables) to get the results.

希望您现在能看到我要解决的区别。 从上方可以看到, 函数和可观察值都是惰性的 。 我们需要调用(函数)或订阅(可观察的)以获得结果。

Subscriptions to observables are quite similar to calling a function. But where observables are different is in their ability to return multiple values called streams (a stream is a sequence of data over time).

可观察对象的订阅与调用函数非常相似。 但是,可观察变量的不同之处在于它们返回称为流的 多个 的能力(流是一段时间内的数据序列)。

Observables not only able to return a value synchronously, but also asynchronously.

可观察对象不仅可以同步返回值,而且还可以异步返回值。

var observable = Rx.Observable.create((observer: any) =>{observer.next(‘Hi Observable’);setTimeout(()=>{observer.next(‘Yes, somehow understandable!’)}, 1000)   observer.next( ‘Am I understandable?’ );
})output :‘Hi Observable’
‘Am I understandable?’ 
Yes, somehow understandable!’.

In short, you can say observables are simply a function that are able to give multiple values over time, either synchronously or asynchronously.

简而言之,您可以说observables只是一个函数,它可以随时间推移以同步或异步方式提供多个值

You now have an outline about observables. But let’s understand them more by looking into different phases of observables.

现在,您有了有关可观察物的概述。 但是,让我们通过观察可观察物的不同阶段来更深入地了解它们。

可观察的阶段 (Observable Phases)

We have already seen from the above example how observables create and execute and come into play by subscription. Hence, there are four stages through which observables pass. They are:

从上面的示例中我们已经看到了可观察对象如何创建和执行以及如何通过订阅发挥作用。 因此,可观察性经历了四个阶段。 他们是:

  1. Creation

    创建

  2. Subscription.

    订阅。

  3. Execution

    执行

  4. Destruction.

    破坏。

Creation of an observable is done using a create function.

创建一个可观察的 使用create 函数完成

var observable = Rx.Observable.create((observer: any) =>{
})

To make an observable work, we have to subscribe it. This can be done using the subscribe method.

要进行可观察的 工作 ,我们必须订阅它。 可以使用subscription方法完成此操作。

observable.subscribe((data)=>{console.log(data);    
})

Execution of observables is what is inside of the create block. Let me illustrate with the help of an example:

可观察对象的执行是create块内部的内容。 让我借助一个示例进行说明:

var observable = Rx.Observable.create((observer: any) =>{observer.next(‘Hi Observable’);        setTimeout(()=>{observer.next(‘Yes, somehow understandable!’)}, 1000)   observer.next( ‘Am I understandable?’ );})

The above code inside the create function is observable execution. The three types of values that an observable can deliver to the subscriber are:

上面的代码在create函数中是可以观察到的执行。 可观察可以传递给订户的三种类型的是:

observer.next(‘hii’);//this can be multiple (more than one)observer.error(‘error occurs’) // this call whenever any error occus.Observer.complete(‘completion of delivery of all values’) // this tells the subscriptions to observable is completed. No delivery is going to take place after this statement.

Let’s have a look below to understand all three values:

下面让我们看一下这三个值:

var observable = Rx.Observable.create((observer: any) =>{
try {observer.next(‘Hi Observable’);                                       setTimeout(()=>{observer.next(‘Yes, somehow understandable!’)}, 1000)   observer.next( ‘Am I understandable?’ );observer.complete();observer.next(‘lAST DELIVERY?’ );  // above block is not going to execute as completion notification is      already sent.}
catch(err){observer.error(err);	}})

Last phase that comes into the market is destruction. After an error or a complete notification, the observable is automatically unsubscribed. But there are cases where we have to manually unsubscribe it. To manually do this task, just use:

进入市场的最后阶段是破坏。 错误或完整通知后,可观察对象将自动取消订阅。 但是在某些情况下,我们必须手动取消订阅 。 要手动执行此任务,只需使用:

var subscription = observable.subscribe(x => console.log(x)); // Later: subscription.unsubscribe();

This is all about the different phases through which an observable passes.

这都是关于可观察的不同阶段。

I think, now, we know what observables are? But what about the other question which is - how observables are different from promises? Let’s find the answer to it.

我想,现在,我们知道什么是可观测值? 但是另一个问题是-可观察性与诺言有何不同? 让我们找到答案。

承诺与可观察 (Promises vs observables)

As we know, promises are for handling async requests and observables can also do the same. But where do they differ?

众所周知,promise用于处理异步请求,可观察对象也可以这样做。 但是它们有何不同?

可观察者是懒惰的,而诺言不是 (Observables are lazy whereas promises are not)

This is pretty self-explanatory: observables are lazy, that is we have to subscribe observables to get the results. In the case of promises, they execute immediately.

这是不言而喻的:可观察变量是惰性的,也就是说我们必须订阅可观察变量才能得到结果。 对于诺言,它们会立即执行。

观察值处理与允诺不同的多个值 (Observables handle multiple values unlike promises )

Promises can only provide a single value whereas observables can give you multiple values.

承诺只能提供一个值,而可观察值可以给您多个值。

观测值可取消 (Observables are cancelable)

You can cancel observables by unsubscribing it using the unsubscribe method whereas promises don’t have such a feature.

您可以通过使用unsubscribe方法取消订阅可观察对象来取消它,而Promise没有这样的功能。

观测值提供许多运算符 (Observables provide many operators)

There are many operators like map, forEach, filter etc. Observables provide these whereas promises does not have any operators in their bucket.

有很多运算符,例如map forEach filter等。Observables提供了这些,而promises的存储桶中没有任何运算符。

These are features that makes observables different from promises.

这些功能使可观察的事物与承诺不同。

Now, it's time to end. I hope you have a better understanding of the hot topic of observables!

现在,该结束了。 希望您对可观察的热点话题有更好的了解!

Thanks for reading!

谢谢阅读!

翻译自: https://www.freecodecamp.org/news/what-are-observables-how-they-are-different-from-promises/


http://lihuaxi.xjx100.cn/news/237943.html

相关文章

Android组件框架:Android组件管理者ActivityManager

关于作者 郭孝星,程序员,吉他手,主要从事Android平台基础架构方面的工作,欢迎交流技术方面的问题,可以去我的Github提issue或者发邮件至guoxiaoxingse163.com与我交流。 第一次阅览本系列文章,请参见导读&a…

区块链推广所需的三个关键因素

想知道更多关于区块链技术知识,请百度【链客区块链技术问答社区】 链客,有问必答!在现有产业中推广区块链的3个关键 区块链的设计是为了展示无可辩驳的真理,而不是依靠权威的控制。虽然这听起来很理想,但问题是&#…

Wireshark使用教程:不同报文颜色的含义

“ Wireshark色彩规则。”在Wireshark主界面,报文会显示各种各样的颜色,它们表示不同的含义。这些颜色,是由色彩规则控制的。对这些颜色进行适当的了解,对分析报文有很大帮助。01—设置色彩规则有两个入口,一个在报文上…

区块链社交APP协议分析预告

2017年,比特币的火热,直接导致了代币市场的繁荣;2018年,作为信用体系的未来解决方案,区块链引发了互联网原住民的淘金热。作为风口上的引流神器,区块链技术与社交网络结合起来,产生了一系列区块…

使用FortJs使用现代JavaScript开发Node.js

介绍 (Introduction) Nodejs gives you the power to write server side code using JavaScript. In fact, it is very easy and fast to create a web server using Nodejs. There are several frameworks available on Node package manager which makes the development eve…

[Doctrine Migrations] 数据库迁移组件的深入解析三:自定义数据字段类型

自定义type 根据官方文档&#xff0c;新建TinyIntType类&#xff0c;集成Type&#xff0c;并重写getName&#xff0c;getSqlDeclaration&#xff0c;convertToPHPValue&#xff0c;getBindingType等方法。 TinyIntType.php完整代码&#xff1a; <?php namespace db\types; …

(转)如何修改maven的默认jdk版本

背景&#xff1a;在maven的配置文件中配置编译的jdk插件&#xff0c;就不需要在eclipse中进行重新的指定了。 问题 1、创建maven项目的时候&#xff0c;jdk版本是1.5版本&#xff0c;而自己安装的是1.7或者1.8版本。 2、每次右键项目名-maven->update project 时候&#xff…

区块链在未来是否还有前途?

想知道更多关于区块链技术知识&#xff0c;请百度【链客区块链技术问答社区】 链客&#xff0c;有问必答&#xff01;区块链协议概述&#xff08;第二部分&#xff09; 简化付款确认 可以在不运行完整网络节点的情况下验证支付。用户只需要保存最长的工作证明链的块头副本&…