Skip to content

Instantly share code, notes, and snippets.

@Hlight
Last active January 2, 2019 15:58
Show Gist options
  • Select an option

  • Save Hlight/08d02e39a7eb707eb1cdca013f520d0a to your computer and use it in GitHub Desktop.

Select an option

Save Hlight/08d02e39a7eb707eb1cdca013f520d0a to your computer and use it in GitHub Desktop.
JS Async Patters: Promises // source https://jsbin.com/zekaxur
/*
https://app.pluralsight.com/player?course=javascript-best-practices&author=jonathan-mills&name=javascript-best-practices-m4&clip=2&mode=live
Async Patters: Promises
*/
//-------------------
// # WITHOUT PROMISE:
//-------------------
// # Mock Async Call (callback)
function asyncMethod(msg, cb){
setTimeout(function(){
console.log(msg);
cb();
}, 500);
}
// # Initial "christmas-tree code" ugly, not ideal!
asyncMethod('Open DB Connection', function(){
asyncMethod('Find User', function(){
asyncMethod('Validate User', function(){
asyncMethod('...do stuff', function(){});
})
})
})
//----------------
// # WITH PROMISE:
//----------------
// # Mock Async Call (promise)
function asyncMethod(msg){
return new Promise(function(fulfill, reject) {
setTimeout(function(){
console.log(msg);
fulfill();
}, 500);
});
}
// # 'then' still ugly :(
asyncMethod('Open DB Connection')
.then(function(){
asyncMethod('Find User')
.then(function(){
asyncMethod('Validate User')
.then(function(){
asyncMethod('...do stuff')
.then(function(){});
})
})
})
// --
// # Use Functions (not returning promises)
function findUser(){
asyncMethod('Find User')
.then(validateUser)
}
function validateUser() {
asyncMethod('Validate User')
.then(doStuff)
}
function doStuff() {
asyncMethod('...do stuff')
.then(function(){});
}
asyncMethod('Open DB Connection')
.then(findUser)
// --
// # Use Functions (return promises)
function findUser(){
return asyncMethod('Find User')
}
function validateUser() {
return asyncMethod('Validate User')
}
function doStuff() {
return asyncMethod('...do stuff')
}
asyncMethod('Open DB Connection')
.then(findUser)
.then(validateUser)
.then(doStuff);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment