Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async/await clarity, with sleep example

I am trying to get hang of async/await with below implementation but it is not working as expected

    public static async sleep(ms: number): Promise<void> {
        await Utilities._sleep(ms);
    }

    private static _sleep(ms: number): Promise<{}> {
        return new Promise((resolve: Function) => setTimeout(resolve, ms));
    }

_sleep will resolve promise after n milliseconds, and await should sleep till that time..

but below test of mine is failing

it("should sleep for 500 ms", ()=> {
    const date1 = (new Date()).getTime();
    Utilities.sleep(500);
    const date2 = (new Date()).getTime();
    chai.expect(date2 - date1).to.least(500);
})

with message

 sleep should sleep for 500 ms FAILED
    AssertionError: expected 2 to be at least 500

my understanding was: sleep will await till the promise from _sleep is resolved (which as per setTimeout will resolve after 500ms)

EDIT

the test framework in mocha

like image 304
harishr Avatar asked Jan 04 '23 23:01

harishr


1 Answers

You have not waited for your sleep() call (as described by the user @igor in the comments of your question):

Simplified version:

async function sleep(ms: number) {
    await _sleep(ms);
}

function _sleep(ms: number) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}

console.time('start')
sleep(500).then(() => {
    console.timeEnd('start')
})

// If your test runner supports async:
it("should sleep for 500 ms", async () => {
    const date1 = (new Date()).getTime();
    await sleep(500);
    const date2 = (new Date()).getTime();
    chai.expect(date2 - date1).to.least(500);
})
like image 123
unional Avatar answered Feb 27 '23 00:02

unional