Typescript – async / await clarity, with sleep example

I tried to get async / await suspended through the following implementation, but it didn't work 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 parse promise in n milliseconds and wait until that time

But my test failed

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);
})

And message

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

My understanding is: sleep will wait until_ Sleep's commitment is resolved (it will be resolved after 500ms according to setTimeout)

edit

Mocha's test framework

Solution

You haven't waited for the sleep() call (as described by the user @ Igor in the question comment):

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);
})
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>