yarn add async-is-fun
// or
npm install --save async-is-fun
- See: test/defer.js For usage.
An overlooked pattern for Promise usage, returns An old school self contained deferred object. A fun use of this is waiting for async instantiation in class constructors.
Type: object
Properties
resolvefunction (any) resolve the Promise with value.rejectfunction (any) reject the Promise with value.promisePromise
Examples
const defer = require('async-is-fun').defer
class AsyncConstructor {
constructor(promise){
this.Promise = promise.promise
setTimeout(() => {
promise.resolve(Math.random())
}, 1000)
}
}
let later = new AsyncConstructor(defer())
let evenLater = new AsyncConstructor(defer())
Promise.all([later.Promise, evenLater.Promise])
.then((results)=>{
console.log(results) // [ 0.17888717674897858, 0.8638054083464473 ]
})- See: test/delayPromise.js For usage.
Delays resolution of a Promise by [time] amount, resolving [value]
Yes, it is true that plenty of other libraries implement this method, but is included here because it is used internally and could save someone from having to load a second bigger library like bluebird.
Parameters
timenumber in milliseconds
Examples
const delay = require('async-is-fun').delay
Promise.resolve('Wait for it')
.then(delay(1000))
.then((result)=>{
console.log(result) // 'wait for it'
}Returns function (any)
- See: test/retryUntil.js For usage.
- See: src/growIt.js For the timeout growth function.
Retry a Promise returning function
Type: function
Parameters
funfunction A promise or value returning function, values will be wrapped in a Promise.configobject? The optional configuration object.config.timeoutobject Initial timeout value before retry. (optional, default250)config.boundobject Upper bound of the computed timeout. (optional, default1000)config.growthobject Growth rate of the timeout per iteration. src/growIt.js (optional, default0.2)config.triesobject Number of attempts before the promise is rejected. (optional, default10)config.returnErrorsobject Number of errors to report if [func] throws or rejects. (optional, default5)
Examples
const retryUntil = require('async-is-fun').retryUntil
Promise.resolve({msg: 'Retry a bunch', value: 10})
.then(retryUntil((value)=>{
//Value is passed through.
console.log(value) // {msg: 'Retry a bunch', value: 10}
return somePromiseReturningFun(9)
.then((count)=>{
console.log(count) // 9
let total = count + value
//If a truthy value is returned the promise will resolve with that value.
if(total === 15){
return {total: total}
}
//If we return false, the method will retry after the timout expires.
return false
})
}))
.then((result)=>{
console.log(result) // {total: 19}
}Returns function (value) Returns a Promise returning function that will resolve the first truthy value returned or resolved by the provided function. It will reject when all attempts are exhausted.