Created
November 18, 2017 03:06
Star
You must be signed in to star a gist
Async Await gentle introduction
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
// 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'); |
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
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'); | |
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
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