deferrable.onFailure()

This commit is contained in:
Julien Fontanet
2016-01-14 11:17:49 +01:00
parent 36a3012de2
commit 233124ef50

View File

@@ -2,6 +2,11 @@ import bind from 'lodash.bind'
import isArray from 'lodash.isarray'
import isFunction from 'lodash.isfunction'
import {
isPromise,
pFinally
} from './utils'
// ===================================================================
const {
@@ -10,11 +15,6 @@ const {
getOwnPropertyDescriptor
} = Object
const _isPromise = value => (
value != null &&
typeof value.then === 'function'
)
// ===================================================================
// See: https://github.com/jayphelps/core-decorators.js#autobind
@@ -136,6 +136,33 @@ export const deferrable = (target, name, descriptor) => {
return newFn
}
// Deferred functions are only executed on failures.
//
// i.e.: defer.clear() is automatically called in case of success.
deferrable.onFailure = (target, name, descriptor) => {
let fn
function newFn (defer) {
const result = fn.apply(this, arguments)
return isPromise(result)
? result.then(result => {
defer.clear()
return result
})
: (defer.clear(), result)
}
if (descriptor) {
fn = descriptor.value
descriptor.value = newFn
} else {
fn = target
target = newFn
}
return deferrable(target, name, descriptor)
}
// -------------------------------------------------------------------
const _ownKeys = (