Sarah Zinger
@SarahsZingers
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++;
}
}
1
2
3
Synchronous Single Threaded
Multi Threaded
Asynchronous Single Threaded
1
2
3
The Dream: Synchronous Single Threaded
Asynchronous Single Threaded
The Reality: Synchronous Single Threaded
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!");
TweetDatabase.getTweet(function(err, tweet){
tweet.getAllReTweets(function(err, retweets){
retweets.getUsers(function(err, users){
users[0].follow();
})
})
})
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! :(")
}
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();
})
})
})
//inside a bunch of nested callbacks:
var users = retweets.getUsers();
//later...
users[0].follow();
//later...
users.addAllToList()
var promisedUsers = retweets.getUsers();
// later...
promisedUsers.then(function(users){
users.followAll();
})
// later...
promisedUsers.then(function(users) {
users.addToList();
})
var promisedUsers = Q.promise(function (success, failure) {
retweets.getUsers(function(err, users){
if(err) {
failure(err)
} else {
success(users)
}
})
}
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)
})
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)
})
Sarah Zinger
sarahzinger.com
SarahsZingers