Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
executing code inside setTimeout in a asynchronous function?

A simple script, what I am trying to achieve is pushing new item in the append method, and using asynchronous functions

I'm trying to understand how then and catch works instead of using them without understanding how they work inside ( using axios or something )

The push has to be executed after 3 seconds

I tried to use the resolve method inside setTimeout but I am getting an error, because resolve isn't recognized, I am returning a Promise because I can't await a setTimeout

<script>

    async function test(terms) {
        let termss = await append(terms);
        return [termss[termss.length - 2], termss[termss.length - 1]]
    }

    async function append(arr) {
        var arrr = arr;

        const waitFor = () => new Promise(resolve => {
            setTimeout((resolve) => {
                arrr.push("Taoufiq")
                arrr.push("understands");
            }, 3000)
        });

        await waitFor();

        return arrr;
    }

    test([1, 2, 3, 9]).then((result) => {
        console.log(result)
    })

</script>

Ayy help on this to understand how this works ?

My expected result is returning an array with ["Taoufiq", "understands"]

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should be able to do what you want with the following code:

async function test(terms) {
    let termss = await append(terms);
    return [termss[termss.length - 2], termss[termss.length - 1]]
}

async function append(arr) {
    return new Promise(resolve => {
        setTimeout(() => {
            arr.push("Taoufiq")
            arr.push("understands");
            resolve(arr)
        }, 3000)
    });
}

test([1, 2, 3, 9]).then((result) => {
    console.log(result)
})

So you have to return the new Promise inside append function and use the resolve method that Promise constructor gives to you inside the setTimemout.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda