![](/img/trans.png)
[英]How does an async mocha test resolve without returning a promise or invoking the done callback
[英]How does the qunit knows when the async test callback is complete even though the tests does not return promise?
Qunit 一個一個地執行異步測試,但是它怎么知道測試完成了,因為測試沒有返回 qunit 可以等待的 Promise?
在這個演示示例中https://jsfiddle.net/6bnLmyof/
function squareAfter1Second(x) {
const timeout = x * 1000;
console.log("squareAfter1Second x:", x);
return new Promise(resolve => {
setTimeout(() => {
resolve(x * x);
}, timeout);
});
}
const { test } = QUnit;
test( "an async test", async t => {
console.log("starting test1");
t.equal( await squareAfter1Second(3), 9 );
t.equal( await squareAfter1Second(4), 16 );
});
test( "an async test2", async t => {
console.log("starting test2");
t.equal( await squareAfter1Second(1), 1 );
});
有 2 個異步測試,它們一一運行。 測試將宏任務 (setTimeout) 發布到事件循環,但盡管測試未返回承諾,但 qunit 以某種方式能夠等待測試完成。 此外,在qunit的源代碼中,不存在 await 關鍵字。
異步函數總是返回 Promises,一旦到達它們的塊末尾(或到達return
值)就會解決。 因此,即使沒有明確返回任何內容, await
意味着兩個異步回調都隱式返回在函數中的所有await
完成后解析的承諾。 所以test
只需要遍歷它調用的每個回調函數,並await
每個調用。
下面是一個示例,說明您也可以自己實現這一點,而無需更改squareAfter1Second
任何代碼或test
調用:
const queue = [] const test = (_, callback) => { queue.push(callback); }; function squareAfter1Second(x) { const timeout = x * 1000; console.log("squareAfter1Second x:", x); return new Promise(resolve => { setTimeout(() => { resolve(x * x); }, timeout); }); } test( "an async test", async t => { console.log("starting test1"); t.equal( await squareAfter1Second(3), 9 ); t.equal( await squareAfter1Second(4), 16 ); }); test( "an async test2", async t => { console.log("starting test2"); t.equal( await squareAfter1Second(1), 1 ); }); (async () => { for (const callback of queue) { console.log('Awaiting callback...'); await callback({ equal: () => void 0 }); console.log('Callback done'); } })();
這就是await
的全部意義(異步等待承諾結果,然后才繼續)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.