JavaScript: mostrare l'avanzamento dei task eseguiti in background

JavaScript: mostrare l'avanzamento dei task eseguiti in background

In JavaScript possiamo mostrare nel frontend l'avanzamento dei task in background gestiti con le Promise.

Abbiamo una serie di task gestiti tramite Promise.


'use strict';

function first() {
    return new Promise(function( resolve, reject ) {
        setTimeout(function() {
            resolve( 'First task done.' );
        }, 1000);
    });
}

function second() {
    return new Promise(function( resolve, reject ) {
        setTimeout(function() {
            resolve( 'Second task done.' );
        }, 2000);
    });
}

function third() {
    return new Promise(function( resolve, reject ) {
        setTimeout(function() {
            resolve( 'Last task done.' );
        }, 3000);
    });
}

Nel frontend possiamo visualizzare un indicatore di stato che mostri quando l'ultimo task รจ stato completato. Useremo Promise.all() per eseguire i task in modo sequenziale.


document.addEventListener('DOMContentLoaded', () => {
   document.querySelector('#start').addEventListener('click', () => {
        document.querySelector('#loader').style.display = 'inline';
        Promise.all([ first(), second(), third() ]).then(function( values ) {
            document.querySelector('#loader').innerText = values[2];
       });

   });
});

In un'applicazione reale i tre task corrisponderebbero ad altrettante operazioni AJAX in background di cui vogliamo mostrare il completamento.

Demo

JavaScript: show Promise's progress

Torna su