我試圖讓下面執行異步/等待着掛但預期之後n毫秒異步/等待清晰,睡眠例如
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
會解決承諾它不工作,伺機應該sleep
到那時..
但低於礦的測試失敗
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的將500毫秒後解決)
編輯
在mocha
當您調用'Utilities.sleep(500);'請參閱https://github.com/jasmine/jasmine/issues/923 – Igor
'async'函數只是一個函數返回時,您從不等待測試結果一個承諾。調用它不會奇蹟般地將異步代碼轉換爲同步代碼。目前還不清楚問題在哪。它是關於異步函數還是測試?如果前者,那麼測試例子是無關緊要的。如果是後者,那麼這個問題就不存在了,甚至沒有提到你使用的是哪個測試框架。那麼是關於測試還是關於異步/等待? – estus
@estus我知道它不是魔術,因此試圖學習一些我不明白的東西。問題是關於在javascript中實現'sleep' –