Created
March 5, 2020 04:46
-
-
Save zxhfighter/d8bb25d972f9d5d8f7da9ed78db05a5b to your computer and use it in GitHub Desktop.
async demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function sleep(name: string, ms: number) { | |
await new Promise(resolve => { | |
console.log(`${name} sleep ${ms} seconds`); | |
setTimeout(resolve, ms); | |
}); | |
} | |
async function forEachLoop() { | |
const numbers = [1, 2, 3, 4, 5]; | |
const basetime = Date.now(); | |
numbers.forEach(async n => { | |
console.log('forEach in: ', n, 'elapse time: ', Date.now() - basetime); | |
await sleep(`forEach ${n}`, Math.floor(2000 + Math.random() * 1000)); | |
console.log('forEach out: ', n, 'elapse time: ', Date.now() - basetime); | |
}); | |
} | |
async function forOfLoop() { | |
const numbers = [1, 2, 3, 4, 5]; | |
const basetime = Date.now(); | |
for (const n of numbers) { | |
console.log('forOf in: ', n, 'elapse time: ', Date.now() - basetime); | |
await sleep(`forOf ${n}`, Math.floor(2000 + Math.random() * 1000)); | |
console.log('forOf out: ', n, 'elapse time: ', Date.now() - basetime); | |
} | |
} | |
async function main() { | |
console.time('不使用 await'); | |
sleep(`no await`, 5000); | |
console.timeEnd('不使用 await'); | |
console.log('\n'); | |
console.time('使用 await'); | |
await sleep(`use await`, 5000); | |
console.timeEnd('使用 await'); | |
console.log('\n'); | |
console.log('使用 forEach,不会按序执行,注意查看 forEach out 是乱序的'); | |
forEachLoop(); | |
console.log('\n'); | |
console.log('使用 forOf,会按序执行,注意查看 forOf in 和 forOf out 一一对应'); | |
forOfLoop(); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment