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
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With