Pesquisar neste blog

05/08/2020

Async/Await 01 em JavaScript


function esperarPor(tempo = 2000) {
    return new Promise(function (resolve){
        setTimeout(() => resolve(), tempo )
    })
}

esperarPor(2000)
    .then(() => console.log('Excecutando promise 1...'))
    .then(esperarPor)
    .then(() => console.log('Excecutando promise 2...'))
    .then(esperarPor)
    .then(() => console.log('Excecutando promise 3...'))

    //Assíncrono
//Substitindo o código acima, método 1
async function executar() {
    esperarPor(1500)
    console.log('Async/Await 1...');

    esperarPor(1500)
    console.log('Async/Await 2...');

    esperarPor(1500)
    console.log('Async/Await 3...');
}

executar()
console.log();

//Método 2, código síncrono
async function executarNovamente(){
    await esperarPor(1500);
    console.log('Async/Await 1... método 2 ');

    await esperarPor(1500)
    console.log('Async/Await 2... método 2');

    await esperarPor(1500)
    console.log('Async/Await 3... método 2');
}

//executarNovamente()

Promise 05 em JavaScript

function funcionarOuNao(valorchanceErro) {

    return new Promise ((resolve , PromiseRejectionEvent=>{
        try{
            con.log('temp')
            if(Math.random() < chanceErro){
                reject('Ocorreu um ERRO !')
            }else{
                resolve(valor)
            }
        }catch(e){
            reject(e)
        }
    })
}

//gerando uma promessa que não foi tratada
funcionarOuNao('Testando...'0.9)
    .then(v => console.log(`Valor: ${v}`),
        err => console.log(`Erro esp.: ${err}`))
    
    //depois do cath não tem mais informação
    .catch(err => console.log(`Erro: ${err}`))//caso ocorra erro
    .then(() => console.log('Fim !'))