DEV Community

[Comment from a deleted post]
Collapse
 
sebastiandg7 profile image
Sebastián Duque G

Thanks for the article David! I know you have an Angular brackground too, therefore RxJS... Are you aware of any benefits one can get from using web workers that are not present when using Observables or, why not, Promises?

Collapse
 
daviddalbusco profile image
David Dal Busco • Edited

I think that Web Worker addresses another need that Promises/Observables.

Promises are asynchronous operations as they give the promise of a result not yet available (MDN docs).

Observables are asynchronous too.

But, JavaScript is single threaded, therefore yes these operations are asynchron but when their related code is executed ("when the code inside the promise or observable runs") then it uses the single thread and therefore block any other evaluation.

Web Workers are asynchronous too but to the contrary run in separate threads, therefore, when their code is executed, it doesn't block the main single JavaScript thread of the application.

Does that make sense?

P.S.: Here also the "blocking example" of my blog post in which I added a promise. Even it does contains such promise, it would still block the interaction as displayed in the related animated gif.

import {
    IonContent,
    IonPage,
    IonLabel,
    IonButton
} from '@ionic/react';
import React, {useState} from 'react';
import {RouteComponentProps} from 'react-router';

import './Page.css';

const Page: React.FC<RouteComponentProps<{ name: string; }>> = ({match}) => {

    const [countTomato, setCountTomato] = useState<number>(0);
    const [countApple, setCountApple] = useState<number>(0);

    async function incApple() {
        await deferIncApple();
    }

    function deferIncApple(): Promise<void> {
        return new Promise<void>((resolve) => {
            const start = Date.now();
            while (Date.now() < start + 5000) {
            }
            setCountApple(countApple + 1);

            resolve();
        });
    }

    return (
        <IonPage>
            <IonContent className="ion-padding">
                <IonLabel>Tomato: {countTomato} | Apple: {countApple}</IonLabel>

                <div className="ion-padding-top">
                    <IonButton
                        onClick={() => setCountTomato(countTomato + 1)}
                        color="primary">Tomato</IonButton>

                    <IonButton
                        onClick={() => incApple()}
                        color="secondary">Apple</IonButton>
                </div>
            </IonContent>
        </IonPage>
    );
};

export default Page;