Skip to content

Instantly share code, notes, and snippets.

@reynaldot
Last active January 25, 2019 23:45
Show Gist options
  • Save reynaldot/4d222e39c32464691af1c0d66dee3a98 to your computer and use it in GitHub Desktop.
Save reynaldot/4d222e39c32464691af1c0d66dee3a98 to your computer and use it in GitHub Desktop.
Await/Async example. A function marked as "async" is no longer a regular function but an AsyncFunction that wraps whatever it returns in a Promise.
function slowGreeting(timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Hello WorldzZzZzzz');
}, timeout);
})
}
// Assigns the promise value to a variable and returns the variable:
async function getSlowGreeting() {
const greeting = await slowGreeting(1000);
return greeting;
}
// Returns the promise as a value:
async function getAnotherSlowGreeting() {
return slowGreeting(2000);
}
getSlowGreeting().then((greeting) => {
console.log(`getSlowGreeting: ${greeting}`);
});
getAnotherSlowGreeting().then(greeting => {
console.log(`getAnotherSlowGreeting: ${greeting}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment