Skip to content

Instantly share code, notes, and snippets.

@zxhfighter
Created March 5, 2020 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zxhfighter/d8bb25d972f9d5d8f7da9ed78db05a5b to your computer and use it in GitHub Desktop.
Save zxhfighter/d8bb25d972f9d5d8f7da9ed78db05a5b to your computer and use it in GitHub Desktop.
async demo
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