Skip to content

Instantly share code, notes, and snippets.

@moimikey
Created November 23, 2015 21:24
Show Gist options
  • Save moimikey/1a2e7f4c5ebfc0b96eff to your computer and use it in GitHub Desktop.
Save moimikey/1a2e7f4c5ebfc0b96eff to your computer and use it in GitHub Desktop.
a promise in javascript for dummies
// promises != callbacks
function doSomeAction() {
// like $.ajax or $.getJSON from jQuery, fetch will similarly reach out to a remote/local
// destination over HTTP, return a Promise object (the result of the `window.fetch`) that
// we can listen to by simply chaining the `then` method, which is provided by the Promise
// object that is returned by `window.fetch`.
window.fetch(new Request('http://website.com/products.json')).then(function(response) {
imFinished(response)
})
}
function appleTree() {
doSomeAction()
}
function imFinished() {
return 'done!'
}
appleTree()
// --------------------------------------------------------------------
// we have some architectural issues here:
// setting aside the lone `appleTree` function that gets called — and who
// knows what else happens behind the hood — but `appleTree` is sadly
// coupled to `doSomeAction`. Looking at this again, we honestly don't even
// need `appleTree`, but we'll refactor this momentarily.
// `imFinished` seems pretty lonesome too and we really aren't certain as
// to what its job is quite yet. So far I'm not following my own code after
// looking at it an hour later.
// we can refactor the above code to become more reusable and maintainable,
// but also really leverage a Promise-based callback:
function doSomeAction() {
// rather than chaining off of the resolved callback that `fetch` gives us when
// we call it (from within this `doSomeAction` method), we can instead make this
// more reusable by returning the Promise itself, and chain `.then` onto subsequent
// instances of this `doSomeAction` method:
//
// var something = doSomeAction().then(doThis).then(doThat)
// var somethingElse = doSomeAction().then(doAllOfThis)
//
return window.fetch(new Request('http://website.com/products.json'))
}
function appleTree() {
// since `appleTree` gets called initially, we will simply call
// `doSomeAction`, which will return us that `Promise` we wanted.
// this is what gives us the ability to now do `appleTree().then(...)`
return doSomeAction()
}
function imFinished(response) {
console.log(response)
}
// call `appleTree` -> fetch(request) -> Promise(response) -> then -> imFinished(response)
appleTree().then(function(response) {
imFinished(response)
})
// Pro-tip, we can even refactor `appleTree` to become more readable:
appleTree().then(imFinished) // the Promise's callback returns a `response` object as
// the first argument. this just gets relayed to `imFinished`;
// we can simply then re-write this as shown.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment