Last active
January 11, 2024 02:57
-
-
Save alexlatam/9fa8873275dfc490a72b309a2d83317d to your computer and use it in GitHub Desktop.
How it works: Promises - Async/Await - [JavaScript]
This file contains 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
/** | |
* Create a promise and assign it to a variable | |
*/ | |
let promise = new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve('Success!') | |
}, 2000) | |
}); | |
/** | |
* Assign the result of the promise to a variable | |
* In this case we are assigning the result of the promise to the promise_result variable | |
*/ | |
let promise_result = promise.then((successMessage) => { | |
console.log(successMessage) | |
}) | |
console.log(promise_result) | |
/** | |
* output: | |
* Promise { <pending> } // First, the console.log(promise_result) is executed which returns the promise in pending status. | |
* Success! // Then the console.log(successMessage) is executed which returns the promise message | |
*/ | |
/** | |
* To avoid running the console.log(promise_result) before the console.log(successMessage) | |
* An asynchronous function will be created and executed when the promise is resolved. | |
*/ | |
let second_promise = new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve('Success!') | |
}, 2000) | |
}) | |
async function asyncFunction() { | |
let result = await second_promise; // await: Indicates to wait until the pledge is resolved (*) | |
console.log(result); // "done!" | |
} | |
asyncFunction(); | |
/** | |
* output: | |
* Success! // Wait for the promise to resolve and then run the console.log [after 2 seconds]. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment