Badong
Badong

Reputation: 63

NodeJS - Wait for return inside setTimeout

I am trying to learn async/await. I want to wait for the return statement inside my async function. I have to call it several times so I used a setTiemout inside.

EDIT:

//Processing gallery
async function somefunction(){
    async function getPictureR(){

        /* some code */

        if($('.actions > .prev', html)[0]){
            older = $('.actions > .prev', html)[0].attribs.href;
        } else {
            console.log('return');
            return;
        }

        /* some code */

        return new Promise((resolve, reject) => {
            setTimeout(getPictureR, 1 * 1000/2);    
        })
    }
    await getPictureR();
    console.log('getPictureR done');
}

I've tried await getPictureR() but it triggers right after the first call to the function. How can I wait for that return ?

Upvotes: 1

Views: 2347

Answers (1)

Bergi
Bergi

Reputation: 664164

You should never call a promise-returning function, like getPictureR, from an asynchronous (non-promise) callback or inside the new Promise constructor. You also were never resolving the new Promise. You are looking for

return new Promise((resolve, reject) => {
    setTimeout(resolve, 1 * 1000/2);    
}).then(() => {
    return getPictureR(); // do the promise call in a `then` callback to properly chain it
})

But since you're using async/await, you don't need the recursive function and the then chaining anyway. Also you can factor out the setTimeout-in-promise wrapping in a separate helper function:

function delay(t) {
    return new Promise(resolve => setTimeout(resolve, t));
}
async function somefunction() {
    while (true)
        /* some code */

        const prev = $('.actions > .prev', html);
        if (prev.length) {
            older = prev[0].attribs.href;
        } else {
            console.log('return');
            break;
        }

        /* some code */

        await delay(1 * 1000/2);
//      ^^^^^^^^^^^
    }
    console.log('getPicture done');
}

Upvotes: 3

Related Questions