How to make a file return a value after 2 seconds

Asked

Viewed 1,005 times

0

I have the following code:

var age = parseInt(prompt('Digite sua idade: '), 10);

function verificar(age){
    return new Promise(function(resolve,reject){
        if(age > 18){
            resolve()
        }else{
            reject()
        }
    })
}

verificar()
.then(
    setTimeout(
        function(){
            console.log('Maior de 18 anos')
        },2000
    )
    
)
.catch(
    setTimeout(
        function(){
            console.log('Menor de 18 anos')
        },2000
    )
)

The problem is that it gives an error in the console and returns 2 strings. How to solve?

1 answer

2


If you want to simulate a delay in your trial, you should put the setTimeout within your Precedent, before you invoke resolve()

But why doesn’t your code work? Inside then and catch, you should declare a callback function, but you are not declaring a function, you are invoking a function (setTimeout). The function setTimeout returns an integer number for the then, which is basically an identifier for this timeout, and then as the then receives a number instead of receiving a function, it returns an error.

As your code should be:

var age = parseInt(prompt('Digite sua idade: '), 10);

function verificar(age){
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            if(age >= 18){
                resolve()
            } else {
                reject()
            }
        }, 2000)
    })
}

verificar(age)
    .then(function() {
        console.log('Maior de 18 anos')
    })
    .catch(function() {
        console.log('Menor de 18 anos')
    })

Or else using some Arrow functions:

const age = parseInt(prompt('Digite sua idade: '), 10)

function verificar(age) {
    return new Promise((resolve, reject) => 
        setTimeout(() => age >= 18 ? resolve() : reject(), 2000)
    )
}

verificar(age)
    .then(() => console.log('Maior de 18 anos'))
    .catch(() => console.log('Menor de 18 anos'))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.