Skip to content

Instantly share code, notes, and snippets.

@ryunp
Last active February 19, 2020 01:39
Show Gist options
  • Save ryunp/9218e6d4f95d4485a6328d832a1a8e7d to your computer and use it in GitHub Desktop.
Save ryunp/9218e6d4f95d4485a6328d832a1a8e7d to your computer and use it in GitHub Desktop.
/* There are basically 3 solutions for async programming, and 2 of which are with related to Promises. */
/* Promises Notation (#1 & #2) */
// The Promise definition
function timedAction() {
return new Promise(resolve => {
setTimeout(() => { resolve('done') }, 2000)
})
}
// The Promise execution definitions, 1 and 2 are equivalent:
// 1 - Pseuo procedurally with 'await' (error handling: try/catch blocks)
async function saySomething() {
try {
const msg = await timedAction()
console.log('Message: "%s"', msg)
} catch (err) {
console.error(err);
}
}
// 2 - 'Then/Catch' method chaining (error handling: then/catch methods)
function saySomething() {
timedAction()
.then(msg => console.log('Message: "%s"', msg))
.catch(console.error)
}
/* Older Callback Notation (#3) */
// The callback definition
function timedActionCB(cb) {
setTimeout(() => { cb(null, 'done') }, 2000)
}
// 3 - The callback execution definition (error handling: if/else blocks)
function saySomething() {
timedActionCB(function(err, msg) {
if (err) {
console.error(err)
} else {
console.log('Message: "%s"', msg)
}
})
}
/* Execution Result (Regardless of implementation) */
saySomething() // Message: "done" <-- after 2 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment