Skip to content

Instantly share code, notes, and snippets.

@a-r-d
Created November 18, 2017 03:06
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save a-r-d/edd531bee5672a27501fc4cc26cb0df0 to your computer and use it in GitHub Desktop.
Async Await gentle introduction
// function that returns a promise
function getAMessage() {
return new Promise(resolve => {
setTimeout(() => {
resolve("passing this value back...");
}, 2000);
});
}
// function is marked async
async function doAThing() {
console.log('Inside doAThing()');
const result = await getAMessage();
console.log(`result: ${result}`);
return 'doAThing() is done!';
}
// top level, procedural code.
console.log('Calling async func...');
const prom = doAThing();
prom.then((result) => {
console.log('Got result back from promise...', result);
});
console.log('done with async func');
function prom() {
return new Promise(resolve => {
setTimeout(() => {
resolve('some value')
}, 1000);
})
}
console.log('Calling a function that returns a promise');
prom().then((res) => {
console.log(res);
});
console.log('done calling function');
function prom() {
return new Promise((resolve, reject) => {
if(Math.random() > 0.5) {
return reject(new Error('Unlucky error'));
}
resolve('some value')
})
}
console.log('Calling a function that returns a promise');
prom().then((res) => {
console.log(res);
}).catch((err) => {
console.error('err: ', err);
});
console.log('done calling function');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment