Skip to content

Instantly share code, notes, and snippets.

@alexlatam
Last active January 11, 2024 02:57
Show Gist options
  • Save alexlatam/9fa8873275dfc490a72b309a2d83317d to your computer and use it in GitHub Desktop.
Save alexlatam/9fa8873275dfc490a72b309a2d83317d to your computer and use it in GitHub Desktop.
How it works: Promises - Async/Await - [JavaScript]
/**
* 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