README
Lofte
A promise library based of Promises/A+ specification and more
If you do not know anything about promises I recommend you check out the MDN article about promises.
Quick access
An example
var Lofte = require("lofte");
Lofte.resolve("Supports")
.then(function (text) {
return text + " es5"
})
.then(text => `${text} and above`)
.then(console.log) // output: Supports es5 and above
Getting installed
- Install with NPM:
npm install lofte
- (Hopefully a cdn release)
API
Wait there is more than the standards O.O
Synchronous state checks
With Lofte promises you can synchronously check if it is pending, resolved, rejected or canceled.
Takes no parameters and returns a boolean based on if it in that state or not.
promise.isPending()
promise.isResolved()
promise.isRejected()
promise.isCanceled()
callback
.callback(cb)
If you are so obsessed with callbacks. Here you go. Turn the promise into a callback.
promise.callback(function (error, value) {
// Just you typical callback function
})
delay
.delay(ms)
Delay the execution of the promise by x number of milliseconds.
Lofte.resolve('I am a second late')
.delay(1000)
.then(console.log)
cancel
.cancel()
Cancel a Lofte promise.
const lofte = new Lofte((reolve, reject, onCancel) => {
const xhr = new XMLHttpRequest()
// ...
onCancel(() => {
xhr.abort()
})
})
onNotify
.onNotify(handler, ...)
The promise can give of notifications/progression values or events.
promise.onNotify(function (value) {
//...
})
reduce, filter, map
.reduce(cb, [initialValue]) .filter(cb, [thisArg]) .map(cb, [thisArg])
They are exactly like their Array counterparts
finally
.finally(fn)
Called regardless of resolution
promise.finally(function () {
//...
})
fail, lastly
.fail(onRejection) (for catch) .lastly(fn) (for finally)
For enviorments that does not support keywords as function/variable name
promisify
Lofte.promisify(fn, [options])
Turn a function with a callback to a promise returning function.
const readFile = Lofte.promisify(require(fs).readFile)
readFile('anything.txt', 'utf-8').then(console.log)
flow
Lofte.flow(generator)
Basically makes coroutines with es6/es2015 generators.
// going of last example
const readFile = Lofte.promisify(require('fs').readFile)
Lofte.flow(function* () {
try {
const [file1, file2] = yield Lofte.all([
readFile('path/to/file1.txt', 'utf-8'),
readFile('path/to/file2.txt', 'utf-8')
])
} catch (e) {
console.error(e)
}
})
See wiki(Not really done yet) for more