Last active
May 3, 2023 13:21
-
-
Save macchiitaka/1a3a6665bae0e102c3f151044251ff1b to your computer and use it in GitHub Desktop.
[demo] async-await
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
| const SEQUENCE = "sequence"; | |
| const PARALLEL = "parallel"; | |
| /** | |
| * wait | |
| * | |
| * @param s | |
| * @return {Promise} | |
| */ | |
| const wait = (s) => { | |
| return new Promise((resolve) => { | |
| setTimeout(resolve, s * 1000); | |
| }); | |
| }; | |
| /** | |
| * sequence | |
| * | |
| * @return {Promise.<string>} | |
| */ | |
| const sequence = async () => { | |
| await wait(2); | |
| await wait(3); | |
| return SEQUENCE; | |
| }; | |
| /** | |
| * parallel | |
| * | |
| * @return {Promise.<string>} | |
| */ | |
| const parallel = async () => { | |
| const foo = wait(2); | |
| const bar = wait(3); | |
| await foo; | |
| await bar; | |
| return PARALLEL; | |
| }; | |
| console.time(SEQUENCE); | |
| sequence().then(console.timeEnd); // sequence: 5000ms | |
| console.time(PARALLEL); | |
| parallel().then(console.timeEnd); // parallel: 3000ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment