English 中文(简体)
房地与可观测站有何区别?
原标题:What is the difference between Promises and Observables?

<代码>Promise和Observable在安热中有哪些区别?

了解这两个案件的例子将是有益的。 在什么情况下,我们会利用每一种情况?

最佳回答

Promise

<>Promise>Promise,当“inc”号业务完成或失败时,可操作single activity

注:有<编码>Promise/code> Library out that support abolition, but ES6 Promise don t 迄今。

<>可见>

<Observable 就像>>(以多种语文),并允许你在每次活动都要求回响时通过零或更多活动。

通常Observable优于Promise,因为它提供了Promise等特征。 如果你想处理0、1或多个事件,则使用<条码>可保存<>。 你们可以利用每种情况下的同样版本。

。 如果远洋班轮公司向服务器或某些其他昂贵的同业经营申请的结果不再需要,则<代码>的代谢/代码>。 可观测允许你取消订阅,而<编码>Promise即使你不需要通知或结果,也最终会称其成功或失败。

虽然<代码>Promise立即开始,但 可观测只有在您签署时才开始。 因此,观测站被称为 la。

可见operators, 诸如>> >map,forEach,reduce/code>, 类似

There are also powerful operators like retry(), or replay(), ... that are often quite handy. A list of operators shipped with rxjs

Lazy execution allows you to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.

问题回答

<>PromisesObservables 都为我们提供了一些可帮助我们处理asynchronous申请性质的摘要。 他们之间的区别明确见,by Günter 和@Relu。

Since a code snippet is worth a thousand words, let’s go through the below example to understand them easier.

感谢@Christoph 页: 1 a)


聚乙烯 注意处理吉大港山区问题,而不是承诺。

证明你正在建设<>研究功能,应即时显示你的成果。 它很熟悉,但这项任务面临许多挑战。

  • We don t want to hit the server endpoint every time user presses a key. It should flood them with a storm of HTTP requests. Basically, we only want to hit it once the user has stopped typing instead of with every keystroke.
  • Don’t hit the search endpoint with the same query parameters for subsequent requests.
  • Deal with out-of-order responses. When we have multiple requests in-flight at the same time we must account for cases where they come back in unexpected order. Imagine we first type computer, stop, a request goes out, we type car, stop, a request goes out. Now we have two requests in-flight. Unfortunately, the request that carries the results for computer comes back after the request that carries the results for car.

词汇表仅包括两个文档:<代码>app.tswikipedia-service.ts/code>。 在一个现实的世界形势下,我们很可能进一步分裂事情。


下面是Promise-based 执行,没有处理任何所述近端案件。

<代码>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 the Jsonp service to make a GET request against the Wikipedia API with a given search term. Notice that we call toPromise in order to get from an Observable<Response> to a Promise<Response>. Eventually end up with a Promise<Array<string>> as the return type of our search method.

<代码>app.ts

// check the plnkr for the full list of imports
import {...} 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 is not much of a surprise here either. We inject our WikipediaService and expose its functionality via a search method to the template. The template simply binds to keyup and calls search(term.value).

我们不理会的查询方法,即Wikipediaservice的返回,把它作为简单系列的示意图,以使我们能够有*纳克。 通过该格式,并为我们编制一个清单。

See the example of Promise-based implementation on Plunker


实际光辉

让我们改变我们的代码,不要把终点与每一个关键中点混为一谈,而只是在用户停止打字时发出要求。

为了揭开这种超级大国,我们首先需要一个<代码>。 Observable<string>, 该词含有用户类型中的搜索术语。 我们不是对关键活动具有人工约束力,而是能够利用Angular's formControl指令。 为了使用这一指令,我们首先需要将输入我们的应用模块。

<代码>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 {}

一旦进口,我们就可以在模板内使用“Control”,将其命名为“定期”。

<input type="text" [formControl]="term"/>

在我们的构成部分中,我们从@angular/form中创立了一个“”的例子,并将其列为我们组成部分的名词下的一个领域。

在幕后,term自动暴露了Observable<string>,作为我们可以订阅的财产。 现在,我们有<条码>可加利用的加固;斯特鲁特”;,克服用户的投入,如同在<条码>上打上<条码>(400)一样容易。 可见。 新的<代码> Observable<string >, that will only emit a new Value when there haven's has not come new Value for 400 ms.

export class App {
  items: Array<string>;
  term = new FormControl();
  constructor(private wikipediaService: WikipediaService) {
    this.term.valueChanges
              .debounceTime(400)        // wait for 400 ms pause in events
              .distinctUntilChanged()   // ignore if next search term is same as previous
              .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));
  }
}

我们的申请已经表明结果,这是浪费资源,无法再提出搜索要求。 为实现所期望的行为,我们必须做的是,在我们称之为<代码>debouncetime(400)之后,打上“<0>>。

See example of Observable implementation on Plunker

For dealing with out-of-order responses, please check the full article http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

就我在安吉斯使用吉卜赛人,我同意,在通常使用情况下,在使用可观测到的超声器时没有什么区别。 这里没有任何好处在实际中是有意义的。 我希望,我能看到今后出现一些先进的使用案例:


学习更多

<>Promises和Observables将帮助我们在 Java本中利用同步功能。 然而,在许多情况下,这两种做法之间仍然有一些差别,因此,在<条码>上将解决的价值观。 象吉大港山区倡议那样。 另一方面,观测站处理了一系列的同步活动。 两者的主要差别如下:

<<>Promise>:

  • having one pipeline
  • usually only use with async data return
  • not easy to cancel

<>可见>

  • are cancellable
  • are re-triable by nature such as retry and retryWhen
  • stream data in multiple pipelines
  • having array-like operations like map, filter etc
  • can be created from other sources like events
  • they are functions, which could be subscribed later on

此外,我为以下各位树立了图形形象,以直观显示差异:

“Promises

There is one downside of Observables missing in the answers. Promises allow to use the ES7 async/await functions. With them you can write asynchronous code like it would be a synchronous function call, so you don t need callbacks anymore. The only possibility for Observables to do this, is to convert them to Promises. But when you convert them to Promises, you can only have one return value again:

async function getData(){
    const data = await observable.first().toPromise();
    //do stuff with  data  (no callback function needed)
}

进一步读: • 如何就可观测到的海洋生物进行“海洋”?

<>Promises

  1. Definition: Helps you run functions asynchronously, and use their return values (or exceptions), but only once when executed.
  2. Not lazy
  3. Not cancellable (there are Promise libraries out there that support cancellation, but ES6 Promise doesn t so far). The two possible decisions are
    • Reject
    • Resolve
  4. Cannot be retried (Promises should have access to the original function that returned the promise to have a retry capability, which is a bad practice)

<>可见>

  1. Definition: Helps you run functions asynchronously, and use their return values in a continuous sequence (multiple times) when executed.
  2. By default, it is lazy as it emits values when time progresses.
  3. Has a lot of operators which simplifies the coding effort.
  4. One operator retry can be used to retry whenever needed, also if we need to retry the observable based on some conditions retryWhen can be used.

**RxMarbles.com/a>。

两人均只处理不同步的电话。

两者之间的差异:

<>可见>

  1. Emits multiple values over a period of time
  2. Is not called until we subscribe to the Observable
  3. Can be canceled by using the unsubscribe() method
  4. Provides the map, forEach, filter, reduce, retry, and retryWhen operators

<>Promise

  1. 仅具有一次性价值

  2. 2. 要求提供服务,但不得有catch和副渔获物。

  3. 不能取消

  4. 不向任何经营者提供服务

让我说,你们想要走到底。 你们必须根据天气做出决定。 你有三种方式:

  1. 你们看着外观,看着雨季,因此你们改变了思想。 这是一个同步的行动。 你阻止了你做些什么,去了外部检查,看不到结果,然后回到你做什么。

  2. 请你们的兄弟们在你旁边检查今天的天气状况。 在检查天气时,你仍在做你做的事情。 这是一项yn。 你给你的兄弟们带来了任务,等待兑现承诺。 在这种情况下,你正在得到答复,在你收到答复后,你不再得到更新。

  3. 此时,你们登上了电台,听听了24/7天天气状况的天气频道。 在这种情形下,这种反应不是只得到一次答复,而是在进行中。 这一答复是<编码>订阅至<编码>可观测。 可以观察到的是“组合”,订阅是“无线电信号,使你不断更新”。 只要您的电台上台,你就会获得所有最新情况。 在你离开电台之前,你不会丢失任何信息。 当你离开电台时,这是指“未登记的青年”。

I have summarized the differences below,

<>可见>

  1. Observable is just a function that takes an observer and returns a function Observer: an object with next, error.
  2. Observer allows you to subscribe/unsubscribe to its data stream, emit next value to the observer, notify the observer about errors and inform the observer about the stream completion
  3. Observer provides a function to handle next value, errors and end of stream (UI events, http responses, data with web sockets).
  4. Works with multiple values over time
  5. It is cancel-able/retry-able and supports operators such as map, filter, reduce, etc.
  6. Creating an Observable can be -Observable.create() - returns Observable that can invoke methods on -Observer Observable.from() - converts an array or iterable into -Observable Observable.fromEvent() - converts an event into Observable -Observable.fromPromise() - converts a Promise into Observable -Observable.range() - returns a sequence of integers in the specified range

<>Promise

  1. 承诺是一项未来将完成的任务;

  2. 日期改为,由价值>解决;

  3. 不允许例外;

  4. http://www.strong>。

  5. 允诺暴露出一个功能(then)

    - 回到一个新的<><><>/code>;

    -allows for the attachment of that will be executed based on state;

    - 《<<><>条码>中<>handlers<>>>>><>>>>>><>条码><>>>>>>>> ><<<<>t>>>>>>>>>>>>>>>>>>> ><<>条码><>>>>>>>>>>>>> ><>印有<>条码>>>>印有>>>>>>>>>guarante>>>>><>>>>>>>>>>>>>> > > 印有<> 印有<>>>>>>>>>> 印有<>>>>>>>> 印有<>>>>>>>>> 印有<>>>>>>>>>>>> 印有>>>>>>>>>> 印有>>> 印有<>>> 印有<>>>>

I believe all the other answers should clear your doubts. Nevertheless, I just wanted to add that observables are based on functional programming, and I find very useful the functions that come with it like map, flatmap, reduce, zip. The consistency the web achieves especially when it depends on API requests is a brutal improvement.

我强烈建议,因为该文件载有被动反应的正式文件。 我认为,这是这方面最清楚的。

If you want to get into observables, I would suggest this 3-part post: http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/

虽然这是对RxJava的意思,但是这些概念是一样的,它确实作了很好的解释。 在被动式X文件中,每个职能都有等同。 你们必须看着RxJS。

Overview:

  • Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.
  • A Promise can only handle one event, Observables are for streams of events over time
  • Promises can t be cancelled once they are pending
  • Data Observables emit can be transformed using operators

你们总是能够使用一种可观测的办法来处理不合时宜的行为,因为可以观察到的行为具有所有功能,允诺(+外加)。 然而,有时不需要观测站提供的这种额外功能。 然后,进口一个图书馆供图书馆使用,会带来额外的间接费用。

When to use Promises:

如果你有“<>single,作为你想要处理结果的合成物,则使用承诺。 例如:

var promise = new Promise((resolve, reject) => {
  // do something once, possibly async
  // code inside the Promise constructor callback is getting executed synchronously

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//after the promise is resolved or rejected we can call .then or .catch method on it

promise.then((val) => console.log(val))      // logs the resolve argument
       .catch((val) => console.log(val));    // logs the reject argument

So a promise executes some code where it either resolves or rejects. If either resolve or reject is called the promise goes from a pending state to either a resolved or rejected state. When the promise state is resolved the then() method is called. When the promise state is rejected, the catch() method is called.

When to use Observables:

Use Observables when there is a stream (of data) over time which you need to be handled. A stream is a sequence of data elements which are being made available over time. Examples of streams are:

  1. User events, e.g. click, or keyup events. The user generates events (data) over time.
  2. Websockets, after the client makes a WebSocket connection to the server it pushes data over time.

In the Observable itself is specified when the next event happened, when an error occurs, or when the Observable is completed. Then we can subscribe to this observable, which activates it and in this subscription, we can pass in 3 callbacks (don t always have to pass in all). One callback to be executed for success, one callback for error, and one callback for completion. For example:

const observable = Rx.Observable.create(observer => {
  // create a single value and complete
  observer.onNext(1);
  observer.onCompleted();
});

source.subscribe(
  x => console.log( onNext: %s , x),   //  success callback
  e => console.log( onError: %s , e),  //  error callback
  () => console.log( onCompleted )     //  completion callback
 );

// first we log: onNext: 1
//  then we log: onCompleted

在建立可观测站时,需要一种可提供观察员作为理由的反馈功能。 在这位观察员上,您可打电话on Next,onCompleted,onError。 那么,当该表被订阅时,该表就会把相应的呼吁书报到。

我刚才谈到一个问题,即市长是最佳解决办法,我在这里与大家分享,如果这个问题有用的话,我会在这里讨论这个问题(这正是我先前所寻求的答案):

在“Angular2”项目中,我有某种服务,具有一定参数,并填写一份价值清单,以表格的形式将男子人数减少。 当组成构成部分开始时,我需要多次把同一服务称为具有不同参数的同一服务单位,以界定若干不同的下降菜单,然而,如果我简单地将所有变量称为服务,只有最后一部分成功,其余错误就消失了。 数据库的服务收费只能及时处理一项申请。

成功普及所有下降的菜单变量的唯一途径是将服务称为一种方式,使新的申请无法处理,直到最后一项要求完成,而且“Promise / then”机制已经解决了这一问题。

  fetchValueList(listCode): Promise<any> {
      return this.dataSvc.getValueList(listCode, this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
          .map(response => response.json())
          .toPromise();
  }

  initializeDropDowns() {
      this.fetchValueList( First-Val-List )
          .then(data => {
              this.firstValList = data;
              return this.fetchValueList( Second-Val-List )
          }).then(data => {
              this.secondValList = data;
              return this.fetchValueList( Third-Val-List )
          }).then(data => {
              this.thirdValList = data;
          })  }

我界定了该构成部分的职能,然后将DropDowns()改为ngOnit。

独角兽部队的功用是一种假冒,因此,第一件叫随头的人穿着第一个名单Code,而当假装时,回报值就出现在.区的数据变数中,我们可以为此分配数据。 第一变量。 由于该职能已归还数据,我们知道该服务已经完成,而且可以安全地再次使用第二个名单Code,因此,返回价值在下一个.块的数据变数中,我们对此予以分配。 第二类变数。

我们能够按要求把所有变数集中起来,在最后的法典中,我们只是排除了回报声明,并停止了封锁。

这是一种非常具体的使用案例,即我们有一个单一服务,需要多次作为组成部分启动,而且服务必须完成手提并收回价值,然后才能再次被称作,但在这种情况下,宣传/宽容方法是理想的。

Promise:

  • Provide a single future value;
  • Not lazy;
  • Not cancellable;

Observable:

  • Emits multiple values over time;
  • Lazy;
  • Cancellable;
  • Supports map, filter, reduce and similar operators

You can use promises instead of observables when calling HTTP in Angular if you wish.

Promise vs Observable similarity first

  1. 这两条都用于处理合成法。

  2. 请举出许诺的例子。 允诺的施工者通过一个决心的参考功能,在完成某些合成任务时,这种功能会得到某种价值的要求。

    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve("Hello from a Promise!");
      }, 2000);
    });
    
    promise.then(value => console.log(value));
    
  3. 可见的实例。 在这里,我们通过一个可以观察的职能——一个观察员处理“合成”任务。 与承诺中的决心不同的是,它有以下方法,并签署了协议。

  4. 因此,这两者都承担共同的任务。 现在请看差异。

    const observable = new Observable(observer => {
      setTimeout(() => {
        observer.next( Hello from a Observable! );
      }, 2000);
    });
    
    observable.subscribe(value => console.log(value));
    

Promise vs Observable difference

<>Promise

  1. It resolves or reject a single value and can handle a single value async task at a time.
  2. A promise once resolved the async value it completes, can no longer be used.its just one-time use and here it falls short.
  3. Not cancellable
  4. No rxjs support for operators.

<>可见>

  1. • 能够提供多种超常价值。

  2. 用于处理各种事件或价值观。 认为你有许多任务或价值,你希望每次都列入价值,应当自动处理。 如果你把价值推向这一阵列,其所有用户都将自动获得最新价值。

  3. 观测台有助于观察投入的变化、反复的间隔、向所有儿童部分播放的价值观、网上的推动通知等。

  4. Can be cancelled using unsubscribe method anytime.

  5. 另一项承诺是支持游轮经营者。 你们有许多管道操作者主要绘制地图、过滤器、开关卡、结合测试等,以便在安装之前改变可观测的数据。

    Enter image description here

Promise - Provides a single future value. Not lazy. Not cancel-able. It will either reject or resolve.

可观测——提供多种未来价值。 Lazy。 Cancel-able. 它提供了其他方法,如mapfilter<>em>和reduce

Promise emits a single value while Observable emits multiple values. So, while handling a HTTP request, Promise can manage a single response for the same request, but what if there are multiple responses to the same request, then we have to use Observable. Yes, Observable can handle multiple responses for the same request.

<>Promise

const promise = new Promise((data) =>
{ data(1);
  data(2);
  data(3); })
.then(element => console.log(‘Promise ‘ + element));

<><>Output

Promise 1

<>可见>

const observable = new Observable((data) => {
data.next(1);
data.next(2);
data.next(3);
}).subscribe(element => console.log( Observable   + element));

<><>Output

Observable 1
Observable 2
Observable 3

www.un.org/Depts/DGACM/index_spanish.htm 简短回答:

<><><> ><> > ><>> > > 。 它有所有<>程序特征加上额外特征。


www.un.org/Depts/DGACM/index_french.htm

<>Promises:

  • One time use "Return data once"
  • No cancel
  • One listener
  • No socket support

<>可见>

  • Return data many times as data change
  • Support cancel
  • Support socket
  • Support many listeners and notify them when data change
  • Support map, filter, and reduce

<>0> 如果一帮派活动结束或失败,则通知单一事件。

观测站就像一个精炼(多种语言)并允许在每次活动需要回击的情况下至少通过零或更多活动。

经常 较之明智,更可取,因为它突出了明智和更多。 如果你需要处理0、1或各种事件,则可以观察。 你们可以使用类似版本处理每一案件。

<>Promise>: promise emits a single value

www.un.org/Depts/DGACM/index_spanish.htm 例如:

const numberPromise = new Promise((resolve) => {
    resolve(5);
    resolve(10);
});

numberPromise.then(value => console.log(value));
// still prints only 5

<>可见> Emits multiple values over a period of time

www.un.org/Depts/DGACM/index_spanish.htm 例如:

  const numberObservable = new Observable((observer) => {
        observer.next(5);
        observer.next(10);
    });

numberObservable.subscribe(value => console.log(value));
// prints 5 and 10

we can think of an observable like a stream which emits multiple values over a period of time and the same callback function is called for each item emitted so with an observable we can use the same API to handled asynchronous data. whether that data is transmitted as a single value or multiple values over some stretch of time.

<>Promise>:

  • A promise is Not Lazy
  • A Promise cannot be cancelled

<>可见>

  • Observable is Lazy. The "Observable" is slow. It isn t called until we are subscribed to it.
  • An Observable can be cancelled by using the unsubscribe() method
  • An addition Observable provides many powerful operators like map, foreach, filter, reduce, retry, retryWhen etc.

Angular Promises vs Observables

  1. A Promise is eager, whereas an Observable is lazy.
  2. A Promise is always asynchronous, while an Observable can be either synchronous or asynchronous.
  3. A Promise can provide a single value, whereas an Observable is a
    stream of values (from 0 to multiple values).
  4. You can apply RxJS operators to an Observable to get a new tailored stream.

从对教学和文献进行一读来看,我有一点是显而易见的,是多预测的想法。

确保你知道,如果出现违约情况,多种订阅将引发可观察的多重处决。 对单项“吉大港山区”电话的多订阅将引发多种相同的吉大港山区电话,除非您<代码>.共有(<>>/代码>(可调多)。

A promise forces you to deal with one thing at a time, unwrap its data, handle exceptions, has language support for cool things like async/await, and is pretty bare-bones otherwise.

可观测到的是许多传闻和告示,但你们需要理解你与你合作或可以滥用的权力。

Promise:

An Async event Handler - The Promise Object is the final full (orail) of an asynchronous operation, and its result Value.

<>Syntax:new Promise(executor);

www.un.org/Depts/DGACM/index_spanish.htm 例如:

var promise_eg = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve( foo );
  }, 300);
});

promise_eg.then(function(value) {
  console.log(value);
  // expected output: "foo"
});

console.log(promise_eg);

Enter image description here

<>About Promise>:

It has one pipeline, so it will return values only once when it’s called. It’s a one-way handler, so once called you may not able to cancel. Useful syntax you can play around, when() and then().

Observables:

观测站是多面值的收集。 它对“合成”行动确实是一个伟大的做法。 可在上完成。

It acts like stream liner and can be multi pipeline. So once defined, you can subscribe to get return results in many places.

Syntax: import * as Rx from "@reactivex/rxjs"; to init:

Rx.Observable.fromEvent(button, "click"),
Rx.Subject()

等等。

签署:<代码>Rxlogger.getInstance();

www.un.org/Depts/DGACM/index_spanish.htm 例如:

import { range } from  rxjs ;
import { map, filter } from  rxjs/operators ;

range(1, 200).pipe(
  filter(x => x % 2 === 1),
  map(x => x + x)
).subscribe(x => console.log(x));

由于支持多管线,你可以同意造成不同地点的结果,

“Entergram

它比承诺更有可能。

<><>Usage:

It has more possibilities, like map, filter, pipe, map, concatMap, 等等。

下面是承诺和计划方面的一些重要差异;可观测性。

<>Promise

  • Emits a single value only
  • Not cancellable
  • Not sharable
  • Always asynchronous

<>可见>

  • Emits multiple values
  • Executes only when it is called or someone is subscribing
  • Can be cancellable
  • Can be shared and subscribed that shared value by multiple subscribers. And all the subscribers will execute at a single point of time.
  • possibly asynchronous

欲了解更多情况,请参阅

我看到许多人认为,可以观测到的是“可贵”的论据,但是,让“可贵”的灵丹妙药。

function cancellablePromise(body) {
  let resolve, reject;
  const promise = new Promise((res, rej) => {
    resolve = res; reject = rej;
    body(resolve, reject)
  })
  promise.resolve = resolve;
  promise.reject = reject;
  return promise
}

// Example 1: Reject a promise prematurely
const p1 = cancellablePromise((resolve, reject) => {
  setTimeout(() => resolve( 10 , 100))
})

p1.then(value => alert(value)).catch(err => console.error(err))
p1.reject(new Error( denied )) // expect an error in the console

// Example: Resolve a promise prematurely
const p2 = cancellablePromise((resolve, reject) => {
  setTimeout(() => resolve( blop ), 100)
})

p2.then(value => alert(value)).catch(err => console.error(err))
p2.resolve(200) // expect an alert with 200

<>Promise:是ES6的一个特征,它涉及作为同义的编码,在制作时立即执行,这种编号只能带来当时的单一价值,不可取消。 由于现代应用和功能需求的复杂性,如果我们同时履行许多承诺,或在执行之前过滤或进行某种转变,就必须执行复杂的守则:

myPromise.then((resolvedValue) => {
    console.log(resolvedValue);
}, (error) => {
    console.log(error);
});

<>可加利用:是Rxjs图书馆提出的一项目标,有助于我们在 Java本应用中进行被动的方案规划,提供链式和订阅,处理具有可取消优势的复杂应用,同时提供许多价值。 此外,我们可以采用其他运营商的链条,例如> 代码>retry(>,>>>>>>,<>>>>>>>>> <> > 代码>switchMap(, 有助于处理复杂的使用案例和重型用户界面等。

www.un.org/Depts/DGACM/index_spanish.htm 例即时搜查:

search(terms: Observable<string>) {
    return terms.pipe(
      debounceTime(400),
      distinctUntilChanged(),
      switchMap((term) => this.searchEntries(term))
    );
  }

www.un.org/Depts/DGACM/index_spanish.htm 类似许多APICS呼吁:

let character = this.http.get( https://jsonplaceholder.typicode.com/todos );
    let characterHomeworld = this.http.get(
       https://jsonplaceholder.typicode.com/posts 
    );

    forkJoin([character, characterHomeworld]).subscribe((results) => {
      console.log( result ° , results[0]);
      console.log( result 1 , results[1]);
    });

还有一个区别: Global vs. Imported

Promise is a standardbuilding-inbject,而且你可以直接使用。 https://caniuse.com/promises”rel=“nofollow noreferer”> 参看

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve( ready with out any installation );
  }, 300);
});

myPromise
.then(value => { console.log(value) })
.catch(err => { console.log(err) });

Observable,

A Promise is always asynchronous, while an Observable can be either synchronous or asynchronous. Observables return data many times as data change. Promise emits a single value. Observables are lazy collections of multiple values over time. It’s really a great approach for async operations. Promises are not lazy. Observables can be cancelled using unsubscribe(). Promises cannot be cancelled.

A Promise handles a single event when an async operation completes or fails.

许可证在申请中自动执行,而观测站则是 la。 因此,我们必须同意观察数据回来。

我们不能不兑现承诺。 它们将每时执行一次,而观测站却无法登记。

www.un.org/Depts/DGACM/index_spanish.htm 我愿对Observables>加以批评。

我不想过于严重,但我已提出一些关于使用<条码>、可保留<>/代码>的问题,载于<条码>, HTTP/API 电话,载于<条码>、<条码>、React。 虽然我喜欢<条码>可使用,并赞赏其灵活性,但我想知道,这些选择是否始终是正确的选择,特别是在涉及<条码>时。

您可以注意到,<代码>Promises只适用于one-time calls,而Observables可无限期地开放流。 我理解开放式溪流的价值,但从我的经验来看,<代码>长期吉大港湾中心电话<>在大多数商业应用中占使用案例的绝大多数。 现在,如果我不得不使用<代码>Angular。 我经常使用<条码>可使用,其方式基本上为之:<条码>。

www.un.org/Depts/DGACM/index_spanish.htm 我认为,在处理诸如点击事件和数据流等活动流时,有<条码>可使用的潜力,我承认它们在这些方面的价值。 然而,在<代码>HTTP/API calls上,它感到,像我们再尝试将90%的使用案例与这一方法相适应。

我不反对探讨替代技术,但我很想知道,向<条码>倾斜的<转变是否值得其复杂! 尤其是当涉及到吉大港山区。 也许更有意义的是,为大多数使用案例提供一个精干的<代码>Promise-based HTTP解决办法,同时鼓励那些真正需要流出的人直接使用RxJs

从我的角度来看,<代码>Promises是达到单一价值的simple, one-time asynchronous operations的理想。 相比之下,“编码”/编码可使用似乎用于处理错综复杂的数据流,其名称有features,如 la评价、取消、先进转化和排放值构成。

www.un.org/Depts/DGACM/index_spanish.htm 最后,我认为,<条码>Promises 和Observables之间的选择将Promises90%的时间

UPDATE: Swagger/OpenAPI Client Code Generators

Due to the intrinsic nature of Promises, it s easy to retrieve responses from async functions with the await keyword. Considering the fact that not everything or every feature in JavaScript is Observable-friendly, this can raise serious problems with features that are already adapted with Promises but not with Observables. for example, there are great tools like openapi-generator that work very well with generators that use Promises. The most important thing in working swagger/openAPI client code generators is using access_token in a way that to be injected into the generated codes, and getting access_token in a secure way (not in browser storage! Please don t do that!) from the server session is most of the time Promise like. you can always find a way to adapt a getAccessToken function that returns Promise to the generated codes, but with generated/created Observable codes it s painful.





相关问题
Angular matSort not working on Date column by desc

Trying to sort the material table with date column , date format is MM/DD/YYYY ,h:mm A , order of date is not by latest date and time. Anything which i missed from the below stackblitz code. https:/...