Skip to content Skip to sidebar Skip to footer

Nested Async Await Inside Timer - Not Returning The Desired Value

I have to test response of endpoints using Mocha and chai tests. Below is the code for the same : async function getData (userId) { let response; let interval = se

Solution 1:

Don't use setInterval with promises, and never pass an async function as a callback when the returned promise is ignored. In your case, use a loop instead:

async function getData (userId) {
    let response;
    do {
        await delay(10000);
        response = await superagent.get("localhost:3000/user/details/").query({'user': userId}).type('application/json');
    } while(response.body["status"] != 'DONE');

    return superagent.get("localhost:3000/user/details/get").type('application/json');
}

with

functiondelay(t) {
    returnnewPromise(resolve =>setTimeout(resolve, t));
}

Solution 2:

Edited to get rid of the while loop:

You can rewrite getData with async/await and wrapping your interval in a promise. Once the first response is ok, clear the interval, resolve the promise and execute the second call.

In your unit-test simply await this function and then verify the response details. Note that you might want to increase the default mocha-timeout for the test, as this could potentially take a while. Something like:

asyncfunctiongetData(userId) {

    const firstResponsePromise = newPromise(resolve => {
            const interval = setInterval(async() => {
                    const response = await superagent.get('localhost:3000/user/details/').query({
                            'user': userId
                        }).type('application/json');
                    if (response.body['status'] == 'DONE') {
                        clearInterval(interval);
                        resolve();
                    }

                }, 10000)
        });

    await firstResponsePromise;
    return superagent.get('localhost:3000/user/details/get').type('application/json');

}

// unit testit('User Get Data', asyncfunction () {
    const res = awaitgetData(userId);
    expect(res).to.exist;
    expect(res.status).to.equal(200);
    expect(res.body).to.contain('operation');
    expect(res.body["userDetails"]).to.exist;

});

Post a Comment for "Nested Async Await Inside Timer - Not Returning The Desired Value"