tryThisforAWhile: Try something for a while in a javascript promise chain

published Jun 03, 2016 10:20   by admin ( last modified Jun 03, 2016 10:26 )

Uses the promise-retry library. The idea is to have a function that retries something a couple of times, and checks if it succeeds. Failure is defined as the function you're trying is either throwing an exception, which is already handled by promise-retry, or, which is the new thing, failure can also be returning a value that a test function deems false. tryThisforAWhile takes the same parameters as promise-retry, with the addition of a "test" property in the config object, that references the test function. Changes to the code are likely. For example the test functions may in the future return true or false instead of throwing. And the test function should probably be curried so that it can be configured with testing criteria in the pipeline.

Example usage (warning, this is alpha code):

const _ = require('lodash')

const P = require('bluebird')

const repeat = require('promise-retry')

P.resolve('foo')
.then(tryThisforAWhile({retries:3, test:neverAcceptFn}, unreliableNetworkCall))
.then(continueWithSomethingElse)

function acceptFn(item) {
    console.log('Accept function triggered')
    return item
}
function neverAcceptFn(item) {
    console.log('Never accept function triggered')
    // Throw some kind of Error. This is a custom one.
    throw new utils.ApplicationError('Validation error', "I will reject anything")
}

function tryThisforAWhile(config, fn) {
    // accepts a config object according to the specifications of
    // https://www.npmjs.com/package/promise-retry
    // with the addition of a test property that should be assigned
    // a test function which should throw an exception if the test fails,
    // otherwise return the item

    return _.curry(_tryThisforAWhile)(config, fn)

    function _tryThisforAWhile(config, fn, item) {
        return repeat(config, function(retry, number) {
            return fn(item).then(config.test).catch(retry)
        })
    }
}