Home > Net >  executing code inside setTimeout in a asynchronous function?
executing code inside setTimeout in a asynchronous function?

Time:12-19

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"]

CodePudding user response:

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.

  • Related