Debbie Clay

Debbie Clay

1600485773

How to Wait for Promises to Resolve with RxJS Observables

This is a quick example showing how to wait for Promises to resolve with RxJS Observables, so that an Observable waits for a promise to resolve before emitting the next value or executing the next pipe() operator.

The example shows five observable values that get emitted in sequence, each waiting two seconds for a Promise to resolve. It’s built with Angular but the RxJS code isn’t Angular specific and could be used with any front end framework (e.g. React, Vue etc).

Example app component with observables waiting for promises

The app component creates an observable sequence containing five string values using the RxJS of() function.

The observable values are piped through two concatMap() operators before being pushed to the users array in the subscribe() method to be rendered in the UI.

RxJS concatMap operator

The concatMap() operator is used in the example to convert promises into observables by passing it a function that returns a Promise. The concatMap() operator runs each observable in sequence and waits for the previous observable to complete before continuing to the next one, if a Promise is returned in concatMap() then it will wait for the promise to resolve before completing the observable.

NOTE: It’s also possible to convert a Promise to an Observable with the RxJS from() operator, e.g. from(new Promise(resolve => setTimeout(() => resolve(value), 2000));).

import { Component } from '@angular/core';
import { of } from 'rxjs'; 
import { concatMap } from 'rxjs/operators';

@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent {
    values = [];

    constructor() {
        // create observable that emits five values
        const observable = of('Value 1', 'Value 2', 'Value 3', 'Value 4', 'Value 5');

        observable
            .pipe(concatMap(value => {
                console.log(`${value}: first pipe operator (before promise)`);                
                // return a promise that resolves with the specified value after 2 seconds
                return new Promise(resolve => setTimeout(() => resolve(value), 2000));
            }))
            .pipe(concatMap(value => {
                console.log(`${value}: second pipe operator (after promise resolved)`);
                return of(value);
            }))
            .subscribe(value => this.values.push(value));
    }    
}

#rxjs #javascript #web-development #programming #developer

What is GEEK

Buddha Community

How to Wait for Promises to Resolve with RxJS Observables
Debbie Clay

Debbie Clay

1600485773

How to Wait for Promises to Resolve with RxJS Observables

This is a quick example showing how to wait for Promises to resolve with RxJS Observables, so that an Observable waits for a promise to resolve before emitting the next value or executing the next pipe() operator.

The example shows five observable values that get emitted in sequence, each waiting two seconds for a Promise to resolve. It’s built with Angular but the RxJS code isn’t Angular specific and could be used with any front end framework (e.g. React, Vue etc).

Example app component with observables waiting for promises

The app component creates an observable sequence containing five string values using the RxJS of() function.

The observable values are piped through two concatMap() operators before being pushed to the users array in the subscribe() method to be rendered in the UI.

RxJS concatMap operator

The concatMap() operator is used in the example to convert promises into observables by passing it a function that returns a Promise. The concatMap() operator runs each observable in sequence and waits for the previous observable to complete before continuing to the next one, if a Promise is returned in concatMap() then it will wait for the promise to resolve before completing the observable.

NOTE: It’s also possible to convert a Promise to an Observable with the RxJS from() operator, e.g. from(new Promise(resolve => setTimeout(() => resolve(value), 2000));).

import { Component } from '@angular/core';
import { of } from 'rxjs'; 
import { concatMap } from 'rxjs/operators';

@Component({ selector: 'app', templateUrl: 'app.component.html' })
export class AppComponent {
    values = [];

    constructor() {
        // create observable that emits five values
        const observable = of('Value 1', 'Value 2', 'Value 3', 'Value 4', 'Value 5');

        observable
            .pipe(concatMap(value => {
                console.log(`${value}: first pipe operator (before promise)`);                
                // return a promise that resolves with the specified value after 2 seconds
                return new Promise(resolve => setTimeout(() => resolve(value), 2000));
            }))
            .pipe(concatMap(value => {
                console.log(`${value}: second pipe operator (after promise resolved)`);
                return of(value);
            }))
            .subscribe(value => this.values.push(value));
    }    
}

#rxjs #javascript #web-development #programming #developer

Promise.allSettled() vs Promise.all()

Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()

https://www.geekstutorialpoint.com/2020/05/promiseallsettled-vs-promiseall.html

#javascript #promise.all #promise.allsettled #ecma #promise #jquery

RxJS Basics in Examples

Let’s take a look at simple examples of using RxJS, and after that, I hope, you will get the basic idea behind it.

What will be covered in this article:

  • 1. Simplest example
  • 2. Observer
  • 3. Observable
  • 4. Subscription
  • 5. RxJS API List: “index” functions:
  • 5.1 concat
  • 5.2 merge
  • 5.3 forkJoin
  • 5.4 fromEvent
  • 5.5 iif
  • 5.6 defer
  • 6. Http requests using “ajax”

#subscription #observer #asynchronous #rxjs #observables

Javascript Promise Resolve Example | Promise.resolve()

Javascript Promise resolve() is an inbuilt function that returns the Promise object that is resolved with the given value.  If the value is the promise, that promise is returned; if the value is a thenable(i.e., has a “then” method), then returned promise will “follow” that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Javascript Promise Resolve Example

The  promise is the particular  JavaScript object that links a “producing code” and the “consuming code” together. In regular terms, this is the “subscription list”. It is like the producers and consumers’ concept.

The “producing code” takes whatever time it needs to produce the promised result, and a “promise” makes the result available to all of the subscribers when it’s ready.

If the job finished successfully, with the result value.

Promise example

The syntax for Javascript Promise.resolve() is the following.

#javascript #value #javascript promise.resolve

Nat  Grady

Nat Grady

1621428060

Angular Meets RxJS: Higher-order Observables

Introduction

This article belongs to a series called “Angular meets RxJS” in which I try to explain reactive programming using “RxJS” in an “Angular” context the best I can.

Table of contents

Basic concepts

RxJS subjects

RxJS operators (Part 1)

RxJS operators (Part 2)

RxJS operators (Part 3)

“takeUntil” and the “async” pipe

Higher-order observables

Error handling

RxJS schedulers (coming soon)

Mini-project: Build a Pokedex (coming soon)

In this article

As we saw in the article about  “RxJS” operators, a higher-order function in “JavaScript” is a function accepting another function in parameter or returning one. The same concept exists for observables. In this article, we are going to see why it is absolutely critical to understand them and how you can use them to simplify and secure your pipelines.

The situation

Let’s take a common situation as a basis for this article. Say you’re building a “Medium” clone to allow people to write some articles. A very nice feature of “Medium” is that it autosaves your document at regular interval.

To simulate the REST API, I’ll use the “json-server” npm package. If you don’t know it, it’s a very useful package that provides a REST API based on a “JSON” file.

Below are the steps required to set it up, you can skip these if you don’t want to replicate the examples of this article on your computer.

Start by installing “json-server” globally by running the command:

yarn global add json-server

Once this is done, create a file called “db.json” with the following content:

{
    "documents": [
        {
            "id": "1",
            "lastUpdate": null
        }
    ]
}

#observables #angular #rxjs #javascript