本文介绍了异步/等待清晰度,带有睡眠示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下实现来解决异步/等待问题,但无法正常工作

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将在n毫秒后解析承诺,并且应等待sleep直到那个时间.

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

但未通过我的测试

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

有消息

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

我的理解是:sleep将等待直到_sleep的承诺得到解决(按照setTimeout将在500ms后解决)

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

编辑

mocha

推荐答案

您尚未等待sleep()通话(如用户@igor在问题注释中所述):

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

简化版本:

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

这篇关于异步/等待清晰度,带有睡眠示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 17:20