当前位置:网站首页>The difference between promise and observable
The difference between promise and observable
2022-07-02 18:42:00 【Hua Weiyun】
StackOverflow Discussion on :What is the difference between Promises and Observables?
The most praised answer :1777 Fabulous
When an asynchronous operation completes or fails ,Promise A single event is processed .
Be careful : Yes Promise Library support cancellation operation , but ES6 Promise So far, it does not support .
Observable
One Observable Like a Stream( In many languages ), Allow zero or more events to be passed , Where the callback... Is called for each event .
Usually Observable Than Promise More popular , Because it provides Promise The characteristics of . Use Observable, Do you want to deal with 0、1 Or more events are not important . You can use the same... In each case API.
Observable Also ratio Promise Have the advantage of canceling . If the server is no longer needed HTTP The result of a request or some other expensive asynchronous operation ,Observable Your subscription allows you to unsubscribe , and Promise Eventually, successful or failed callbacks will be called , Even if you don't do this, you no longer need to notify or provide results .
although Promise It will start immediately , but Observable It will only start when you subscribe to it . That's why Observable The reason called laziness .
Observable Provides map、forEach、reduce Equal operator , Usage is similar to array .
There are also some powerful operators , Such as retry() or replay() etc. , They are usually very convenient .
Deferred execution allows execution through subscriptions observable Before you create a series of operators , For more declarative programming .
The second answer :374 Fabulous
Illustrate with examples .
Angular Use Rx.js Observables instead of promises To deal with it HTTP.
Suppose you are building a search function , This function should immediately display the results as you type . That sounds familiar , But this task will bring many challenges .
We don't want to access the server endpoint every time a user presses a key , If you do , The server will be heavily HTTP Request flooding . Basically , We just want to trigger... After the user stops typing HTTP request , Instead of triggering each keystroke .
For subsequent requests , Do not use the same query parameters to access the search endpoint .
Handle unordered responses . When we have multiple requests in progress at the same time , We must consider the case where they return in an unexpected order . Imagine , Let's first type computer, stop it , Request , Then type. car, stop it , Request . Now we have two ongoing requests . Unfortunately , Bring the results to computer The request carries the result to car After your request, return .
First, let's see how to use it promise To achieve this requirement . Of course , All the border cases mentioned above have not been dealt with .
wikipedia-service.ts:
import { Injectable } from '@angular/core';import { URLSearchParams, Jsonp } from '@angular/http';@Injectable()export class WikipediaService { constructor(private jsonp: Jsonp) {} search (term: string) { var search = new URLSearchParams() search.set('action', 'opensearch'); search.set('search', term); search.set('format', 'json'); return this.jsonp .get('http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK', { search }) .toPromise() .then((response) => response.json()[1]); }}
We are injecting Jsonp service , To use the given search term pair Wikipedia API issue GET request . Please note that , We call toPromise It's to start from Observable<Response> To Promise<Response>. With a final Promise<Array<string>> As the return type of our search method .
app.ts The implementation of the :
// check the plnkr for the full list of importsimport {...} from '...';@Component({ selector: 'my-app', template: ` <div> <h2>Wikipedia Search</h2> <input #term type="text" (keyup)="search(term.value)"> <ul> <li *ngFor="let item of items">{{item}}</li> </ul> </div> `})export class AppComponent { items: Array<string>; constructor(private wikipediaService: WikipediaService) {} search(term) { this.wikipediaService.search(term) .then(items => this.items = items); }}
There's no surprise here . We inject our WikipediaService And disclose its functions to the template through the search method . The template is simply bound to keyup And call search(term.value).
Let's untie WikipediaService The search method returns Promise Result , And expose it to the template as a simple string array , So we can make *ngFor Loop through it and build a list for us .
Where Observables really shine
Let's change our code , Don't tap the endpoint every time you hit the key , But only when the user stops typing 400 Send request in milliseconds
To reveal such superpowers , We need to get one first Observable<string> , It carries the search terms entered by the user . We can use Angular Of formControl Instructions , Instead of manually binding to keyup event . To use this command , We first need to ReactiveFormsModule Import into our application module .
app.ts:
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { JsonpModule } from '@angular/http';import { ReactiveFormsModule } from '@angular/forms';@NgModule({ imports: [BrowserModule, JsonpModule, ReactiveFormsModule] declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
After import , We can use... In the template formControl And set it to the name “term”.
<input type="text" [formControl]="term"/>
In our component , We from @angular/form Created a FormControl Example , And expose it as the name on the component term Next field .
Behind the scenes ,term Automatically expose a Observable<string> As an attribute we can subscribe to valueChanges. Now we have one Observable<string>, Getting user input is like in our Observable On the call debounceTime(400) It's as simple as . This will return a new Observable<string>, It will only 400 Issue a new value only when no new value appears in milliseconds .
export class App { items: Array<string>; term = new FormControl(); constructor(private wikipediaService: WikipediaService) { this.term.valueChanges .debounceTime(400) // wait for 400ms pause in events .distinctUntilChanged() // ignore if next search term is same as previous .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items)); }}
It would be a waste of resources to make another request for a search term that our application has displayed results . In order to achieve the desired behavior , All we have to do is call debounceTime(400) Call immediately after distinctUntilChanged Operator .
Observable and promise Comparison :
边栏推荐
- QQmlApplicationEngine
- 阿里三面被面试官狂问Redis,简历上再也不敢写'精通'了
- Installation tutorial and simple call of Matplotlib
- What is cloud primordial? This time, I can finally understand!
- 再放宽!这些应届生,可直接落户上海
- 元宇宙链游系统开发(逻辑开发)丨链游系统开发(详细分析)
- 深度神经网络总结
- Web实时通信技术之Websocket
- Rte11 interrupt decoupling function
- The official docker image running container in version 1.5.1 can be set to use MySQL 8 driver?
猜你喜欢
QT official example: QT quick controls - Gallery
Implementation shadow introduction
微信核酸检测预约小程序系统毕业设计毕设(2)小程序功能
Relax again! These fresh students can settle directly in Shanghai
Simulateur nightGod + application de test de capture de paquets Fiddler
Leetcode 面试题 16.17. 连续数列
昨天阿里学长写了一个责任链模式,竟然出现了无数个bug
Leetcode 面试题 17.04. 消失的数字
Leetcode interview question 17.04 Vanishing numbers
Troubleshooting ideas that can solve 80% of faults
随机推荐
MySQL about only_ full_ group_ By limit
Leetcode 面试题 17.04. 消失的数字
Is it safe to buy funds on Alipay account
27:第三章:开发通行证服务:10:【注册/登录】接口:注册/登录OK后,把用户会话信息(uid,utoken)保存到redis和cookie中;(一个主要的点:设置cookie)
SteamOS 3.3 Beta 发布,Steam Deck 中文键盘终于来了
Redis(7)----数据库与过期键
Leetcode 面试题 17.01. 不用加号的加法
Wechat applet video sharing platform system graduation design completion (5) assignment
The official docker image running container in version 1.5.1 can be set to use MySQL 8 driver?
1.5.1版本官方docker镜像运行容器,能设置使用 mysql 8驱动吗?
Simulateur nightGod + application de test de capture de paquets Fiddler
A4988 and 42 stepper motors
Wechat nucleic acid detection appointment applet system graduation design completion (5) task statement
呆错图床系统源码图片CDN加速与破J防盗链功能
Qt Official examples: Qt Quick Controls - Gallery
How to use PS to extract image color and analyze color matching
MySQL 关于 only_full_group_by 限制
Pit encountered during installation of laravel frame
Implementation shadow introduction
【西北工业大学】考研初试复试资料分享