I found out that starting an asynchronous wait can be much slower in some scenarios.
<html>
<script>
function makeAPromise() {
return Promise.resolve(Math.random());
}
function usingPromises() {
const before = window.performance.now();
return makeAPromise().then((num) => {
const after = window.performance.now();
console.log('Total (promises): ', after-before, 'ms');
return num;
})
}
async function usingAwait() {
const before = window.performance.now();
const num = await makeAPromise();
const after = window.performance.now();
console.log('Total (await): ', after-before, 'ms');
return num;
}
function runBoth() {
usingAwait();
usingPromises();
}
runBoth();
</script>
<button onclick="usingPromises()">usingPromises</button>
<button onclick="usingAwait()">usingAwait</button>
<button onclick="runBoth()">both</button>
</html>
Run codeHide resultIMO, console.log in usingPromises
should print similar results with what is in usingAwait
. But actually I get:
Total (promises): 0.25 ms
Total (wait): 2.065 ms
Also, after loading the page, if I click the 'usingPromises' or 'usingAwait' button, I get similar results for each of them. (both work fast when working)
Total (promises): 0.060000000026775524 ms
Total (standby): 0.08999999999650754 ms
But if I click on the “both” button, the “wait” version will be 3-4 times slower than the promises version.
, promises/async-await , , async- "" promises ( ~ 200 ).
- , ? , promises ()? , promises async-?