I Do Async Programming
And so can you (I promise)
Sarah Zinger
@SarahsZingers
var self
class SarahZinger {
constructor() {
super();
this._age = 0;
this._knowsJavascript = false;
}
get isHappy() {
return this._knowsJavascript;
}
changeWorld() {
this._age >=25 ?
this.socialWork():
this.code();
}
birthday() {
this._age++;
}
}
What's Asynchronous Programming?
1
2
3
Synchronous Single Threaded
Multi Threaded
Asynchronous Single Threaded
so what?
1
2
3
The Dream: Synchronous Single Threaded
Asynchronous Single Threaded
The Reality: Synchronous Single Threaded
What's a Callback?
Javascript allows for asynchronous calls
that work something like this
console.log("First");
TweetDatabase.getTweets(function(err, tweets){
console.log("Third!");
console.log(tweets);
});
console.log("Second!");
Callbacks Don't Seem So bad?
TweetDatabase.getTweet(function(err, tweet){
tweet.getAllReTweets(function(err, retweets){
retweets.getUsers(function(err, users){
users[0].follow();
})
})
})
WhY, you no bubble?
try {
TweetDatabase.getTweet(function(err, tweet){
tweet.getAllReTweets(function(err, retweets){
retweets.getUsers(function(err, users){
users[0].follow();
})
})
})
}
catch(err) {
console.log("nested errors do not bubble! :(")
}
The dark Side of Callbacks
TweetDatabase.getTweet(function(err, tweet){
if(err){
console.log("we found an err", err)
}
tweet.getAllReTweets(function(err, retweets){
if(err){
console.log("we found an err", err)
}
retweets.getUsers(function(err, users){
if(err){
console.log("we found an err", err)
}
users[0].follow();
})
})
})
Wouldn't It Be Nice...
//inside a bunch of nested callbacks:
var users = retweets.getUsers();
//later...
users[0].follow();
//later...
users.addAllToList()
With PRomises, You Can.
var promisedUsers = retweets.getUsers();
// later...
promisedUsers.then(function(users){
users.followAll();
})
// later...
promisedUsers.then(function(users) {
users.addToList();
})
WHY NO NESTED CALLBACKS THO?
var promisedUsers = Q.promise(function (success, failure) {
retweets.getUsers(function(err, users){
if(err) {
failure(err)
} else {
success(users)
}
})
}
.then() to save the Day
TweetDatabase.getTweet()
.then(function(tweets){
return tweet.getAllReTweets();
})
.then(function(retweets){
return retweets.getUsers();
})
.then(function(users){
users.followAll();
})
.catch(function(err){
console.log("we found an err", err)
})
Don't Do this
TweetDatabase.getTweet()
.then(function(tweets){
tweet.getAllReTweets()
.then(function(retweets){
retweets.getUsers()
.then(function(users){
users.followAll();
})
})
})
.catch(function(err){
console.log("we found an err", err)
})
Do Keep LEarning
Sarah Zinger
sarahzinger.com
SarahsZingers
I Do Async Programming and So Can You
By Sarah Muenzinger
I Do Async Programming and So Can You
- 1,277