promiz
A proper compact promise (promises/A+ spec compliant) library.
What are promises?
function testPromise(val) {
var deferred = promiz.defer()
setTimeout(function(){
deferred.resolve(val)
}, 0)
return deferred
}
testPromise(22).then(function(twentyTwo){
return 33
}).then(function(thiryThree){
return testPromise(99)
}).then(function(ninetyNine){
return [testPromise(11), testPromise(33), testPromise(55)]
}).all().then(function(list){
return list
}).spread(function(eleven, thirtyThree, fiftyFive){
}).done()
Building your own promises with promiz
Promiz has many helper functions to help you convert regular functions into promises
function testPromise(val) {
var deferred = promiz.defer()
setTimeout(function(){
if (val === 42) {
deferred.resolve('correct')
} else {
deferred.reject(new Error('incorrect input'))
}
}, 0)
return deferred
}
testPromise(42).then()
function testFn(val){
if (val === 42){
return 'correct'
}
throw new Error('incorrect input')
}
promiz.fcall(testFn, 42).then()
function nodeFn(val, callback) {
if (val === 42) {
return callback(null, 'correct')
}
return callback(new Error('incorrect input'))
}
promiz.nfcall(nodeFn, 42).then()
Promise methods
.then()
promise.then(function success(){}, function error(){})
.spread()
promise.then(function(){ return [promise(), promise()] }).spread(function(one, two){ })
.all()
promise.then(function(){ return [promise(), promise()] }).all().then(function(list){ })
.fail()
promise.then(function(){ throw new Error('hello') }).fail(function(err){ })
.done()
promise.done()
.nodeify()
function dualFunction( callback){
return promise.nodeify(callback)
}
dualFunction().then()
dualFunction(function(err, val){ })
Notes
- If your entire promise chain is comprised of syncronous functions, the promise will run syncronously
Licence: MIT