Skip to content

Clamouring Cuscus

Choose a tag to compare

@mudge mudge released this 23 Jan 12:32
· 24 commits to master since this release

Driven by contributions from Rodolphe Belouin, this version of Pacta adds two new functions: mapError and chainError. It also improves support for rejected promises when using map by propagating rejection.

var promise = new Promise();
promise.reject('Type error at line 214');

promise.mapError(function (x) {
  console.log(x);

  return 'Error: ' + x;
}); //=> Rejected promise with "Error: Type error at line 214" as reason

chainError can be used like so:

var criticalAjaxCallThatMayFail = function() {
    var p = new Promise();

    setTimeout(function () {
        if (Date.now() % 2 === 0) {
            p.reject('Request timed out');
        } else {
            p.resolve('This is a critical sentence.');
        }
    }, 2000);

    return p;
};

var getMessage = function (error) {
    if (error) {
        console.error('Error received: ' + error);
        console.log('Retrying...');
    }

    console.log('Sending request...');
    return criticalAjaxCallThatMayFail();
};

/* Retry 2 times if it fails */
getMessage()
    .chainError(getMessage)
    .chainError(getMessage)
    .map(console.log)
    .mapError(console.error);

As ever, consult the README for full usage and API documentation.