JavaScript: async e await

JavaScript: async e await

Questo tipo di costrutto JavaScript serve a gestire le operazioni asincrone evitando di dover utilizzare dei callback.

Supponiamo di avere una Promise che restituisce un risultato positivo in caso di numero pari ed uno negativo in caso di numero dispari. Possiamo scrivere:


'use strict';

const echo = console.log;

const evenOddFunc = () => {
    let randInt = Math.round((Math.random() * 10) + 1);
    return new Promise( (resolve, reject) => {
        if(randInt % 2 === 0) {
            resolve('Resolved with: ' + randInt);
        } else {
            reject('Rejected with: ' + randInt);
        }
    });
};


const testFuncAsync = async () => {
    try {
        let result = await evenOddFunc();
        echo('Promise resolved! ' + result );
    } catch(err) {
        echo('Promise rejected! ' + err);
    }
};


for(let i = 0; i < 10; i++) {
    testFuncAsync();
}

Nel blocco try gestiremo il risultato positivo restituito dalla Promise con il costrutto await, mentre nel blocco catch gestiremo l'errore restituito dalla Promise in caso di numero dispari.

Si noti come la funzione che utilizza questo costrutto deve avere l'operatore async preposto alla dichiarazione del corpo della funzione stessa.

Torna su