Last active
September 27, 2023 20:31
-
-
Save robertoandres24/5e6b87a25ad6bb76ca80778ddc1f1c55 to your computer and use it in GitHub Desktop.
Descripcion con ejemplos de Promises y en conjunto con 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
//promise in a variable | |
let promise = new Promise(function(resolve, reject) { | |
setTimeout(() => resolve("done!"), 1000); | |
}); | |
// resolve runs the first function in .then | |
promise.then( | |
result => console.log(result), // shows "done!" after 1 second | |
); | |
promise.catch( | |
error => console.log(error) | |
) | |
//este codigo se ejecutara siempre primero que la promesa | |
console.log("primero") | |
//promise en una funcion | |
function delay(ms) { | |
return new Promise( function(resolve) { | |
setTimeout(function(){ | |
resolve('resolve inside delay after '+ ms/1000 + ' seconds' ); | |
}, ms) | |
}); | |
} | |
//Normal call to fn that returns a Promise | |
//delay(2000) | |
// .then(data => console.log(data + ' after 2 seconds')); | |
//Not very clean way of call other fn after my promise is resolve | |
//function handlingDelayData() { | |
// delay(2000).then(data => console.log('Handling: ' + data) ) | |
//} | |
//handlingDelayData() | |
//Async/wait way of doit, more sync code to write | |
async function handlingDelayData() { | |
let data = await delay(2000); | |
console.log('handling: ' + data) | |
} | |
handlingDelayData() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment