Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active October 29, 2015 20:06
Show Gist options
  • Save wilmoore/443ba85542e30805fde0 to your computer and use it in GitHub Desktop.
Save wilmoore/443ba85542e30805fde0 to your computer and use it in GitHub Desktop.
Example of the composability of promises especially when you use point-free functions.
'use strict'
/*!
* imports.
*/
const selectn = require('selectn')
/*!
* mock functions.
*/
function start (val) {
if (val) {
return Promise.resolve('success')
} else {
return Promise.reject(new Error('not a success'))
}
}
function failure () {
throw new Error('failure')
}
function data () {
return { status: 'done' }
}
function nope () {
console.log('You might think this will not fire, but you would be wrong')
}
/*!
* main.
* Example of the composability of promises especially when you use point-free functions.
* Uncomment one of the chains below to see it run to completion.
*/
start(1)
.then(console.log) // logs "success"
.then(data)
.then(selectn('status')) // selectn is curried so it returns a getter function with artity of 1 returning value of status key.
.then(console.log) // logs "done" --> since previous item in chain returns done, this logs it.
.then(failure)
.catch(console.error) // logs "[Error: failure]"
.then(nope) // logs "You might think this will not fire, but you would be wrong"
// start(0)
// .then(console.log)
// .then(data)
// .then(selectn('status'))
// .then(console.log)
// .then(failure)
// .catch(console.error) // logs "[Error: not a success]"
// .then(nope) // logs "You might think this will not fire, but you would be wrong"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment