- work at venmo on web team for almost a year
- been an engineer a little longer than that (flatiron school)
- applause, ooh-ing and ah-ing
- lots of things made sense/i could pick up w/ relative ease -- iterating over data, ajax calls -- but others were tougher
- one of the things that didn't make sense when learning js were promises
- what is a promise? if i were to hold this promise in my hand like __________, what would it have to tell me? did it have an answer to the task i'd asked it to perform?
- show some code here, maybe a venmo example
-
in the real world
- according to google:
a declaration or assurance that one will do a particular thing or that a particular thing will happen.
- we make promises all the time
- just the other day, i promised my mom i would call her more often
- i promised my roommates i'd take out the trash
-
in the js world
- according to an article:
a promise represents the eventual result of an asynchronous operation
- synchronous code
- a bunch of statements in a sequence -- executed one after the other
- each statement has to wait for the previous one to finish executing
console.log('one'); console.log('two'); console.log('three');
- metaphor it's like when...
- asynchronous
- takes statements outside of main program flow
console.log('one'); setTimeout(function() { console.log('two'); }, 0); console.log('three');
- metaphor it's like when...
- js is single-threaded and synchronous
- two bits of script can't run at the same time, but rather must run one after the other
- in browsers, js shares a thread w/ lots of other stuff
- generall shares a queue w/ painting, updating styles, handling user actions, etc
- activity in one of these things delays another
- metaphor it's like when...
- (what can make js async is that it has various callback mechanisms)
-
the definition
a promise represents the eventual result of an asynchronous operation
-
so given what we now know about how js is executed...
- provides a simpler alternative for async operations
- allows for other things to execute while another job is being done
- a promise can be
- pending -- outcome tbd
- fulfilled -- completed, and the promise has a value
- rejected -- failed, has a reason why it failed
- settled -- has fulfilled/rejected
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
- as we saw earlier, we can use them straight out of js
- there are also lots of libraries available
- q, bluebird, when, winjs, rsvpjs, jquery
- personal favs: q and bluebird