Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!