Introduction to Alternative Async Primitives
# PRESENTING BROKEN PROMISES
# PRESENTING BROKEN PROMISES
# PRESENTING BROKEN PROMISES
# PRESENTING BROKEN PROMISES
const promise = new Promise((resolve, reject) => { console.log(value) })
// promise is not reusable because it's already been called!
const promiseLazy = () => new Promise((resolve, reject) => { console.log(value)})
// wrapping a promise in a function is just a promise getter
// if we allow promises to lazy we can
const promiseAPlusPlus = fetchButBetter('api.cool/123/details').then(parse).then(map)
promiseAPlusPlus.run('adam#123')
// Alternatively Brian McKenna
promiseAPlusPlus.done()
# PRESENTING BROKEN PROMISES
// Assumes promises are lazy
const query = clientDB
.map(fnMapValue) // map over value like we would with arrays
.flatMap(value => anotherAction(value)) // flatten a value like we would arrays
// Run the query
query.run('connection123')
const query = clientDB('connection123')
.map(fnMapValue) // map over value like we would with arrays
.flatMap(value => anotherPromise(value)) // flatten a value like we would arrays
// Run the query
query.done()
# PRESENTING BROKEN PROMISES
// If a promise has an explicit error to be handled
const getDBData = (id) => {
db.conncet()
return db.query(id)
}
getDBData
.onRejected((error) => {
switch error {
// a more useful switch to handle different errors
}
})
.done(res => {}) // uncaught exceptions prevent the Promise from settling
# PRESENTING BROKEN PROMISES
// Tasks are lazy by default so they can be reused!
// They use Promises under the hood, hence the await (or use .then)
const ioTask = Task.of(1)
await ioTask() // can never fail and returns 1
// or maybe something more practical, also can be resused
// we get common methods for free like map and chain
const result = pipe(
ioTask,
T.map(n => n + 1), // map is array.map
T.chain(n => T.of(n + 2)) // chain is array.flatMap
)
await result() // returns 4
# PRESENTING BROKEN PROMISES
// Under the hood just a Task that returns an Either
const successOnly = TE.right(1)
const failOnly = TE.left(2)
const result = pipe(
successOnly
TE.chain(n => failOnly()),
)
await result() // E.left(2)
// Error handling is explicit if you want to get the result
await result()
.fold(
error => console.log(error),
success => console.log(success)
)
# PRESENTING BROKEN PROMISES
# PRESENTING BROKEN PROMISES