- demo: different ways to get resolve (return) value from a
promise - type: full code example
- language: javascript
Last active
June 29, 2021 03:30
-
-
Save jyydev/958d057981a33882f24a6bd86bc7f689 to your computer and use it in GitHub Desktop.
promise, async await, .then
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
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>ref js fetch promise</title> | |
| </head> | |
| <body> | |
| <center> | |
| <h1>promise async await</h1> | |
| <p>Refer console log for info.</p> | |
| </center> | |
| <script src="./index.js"></script> | |
| <script src="https://gist.github.com/jyydev/958d057981a33882f24a6bd86bc7f689.js"></script> | |
| </body> | |
| </html> |
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 url = 'https://api.github.com/'; | |
| const promise = new Promise((resolve, reject) => { | |
| resolve('promise returned'); | |
| }); | |
| // method 1 | |
| async function run1() { | |
| const rs = await promise; | |
| console.log('async:', rs); | |
| } | |
| run1(); | |
| // method 2 | |
| const run2 = async () => { | |
| const rs = await promise; | |
| console.log('async:', rs); | |
| }; | |
| run2(); | |
| // method 3 | |
| (async () => { | |
| const rs = await promise; | |
| console.log('async instant:', rs); | |
| })(); | |
| // method (.then) | |
| promise.then((rs) => { | |
| console.log('.then:', rs); | |
| }); | |
| // method (.then) + catch | |
| promise | |
| .then((rs) => { | |
| console.log('.then + catch:', rs); | |
| }) | |
| .catch((e) => { | |
| console.log(e); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment