async/await clarity, with sleep example

Viewed 5880

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

2 Answers
Related