Skip to content

Latest commit

 

History

History
362 lines (268 loc) · 11 KB

README.md

File metadata and controls

362 lines (268 loc) · 11 KB

eslint-plugin-promise

Enforce best practices for JavaScript promises.

js-standard-style travis-ci npm version

Installation

You'll first need to install ESLint:

$ npm install eslint --save-dev

Next, install eslint-plugin-promise:

$ npm install eslint-plugin-promise --save-dev

Note: If you installed ESLint globally (using the -g flag) then you must also install eslint-plugin-promise globally.

Usage

Add promise to the plugins section of your .eslintrc configuration file. You can omit the eslint-plugin- prefix:

{
    "plugins": [
        "promise"
    ]
}

Then configure the rules you want to use under the rules section.

{
    "rules": {
        "promise/always-return": "error",
        "promise/no-return-wrap": "error",
        "promise/param-names": "error",
        "promise/catch-or-return": "error",
        "promise/no-native": "off",
        "promise/no-nesting": "warn",
        "promise/no-promise-in-callback": "warn",
        "promise/no-callback-in-promise": "warn",
        "promise/avoid-new": "warn",
        "promise/no-return-in-finally": "warn",
        "promise/valid-params": "warn"
    }
}

or start with the recommended rule set

{
    "extends": [
        "plugin:promise/recommended"
    ]
}

Rules

recommended rule description
‼️ catch-or-return Enforces the use of catch() on un-returned promises.
‼️ no-return-wrap Avoid wrapping values in Promise.resolve or Promise.reject when not needed.
‼️ param-names Enforce consistent param names when creating new promises.
‼️ always-return Return inside each then() to create readable and reusable Promise chains.
no-native In an ES5 environment, make sure to create a Promise constructor before using.
⚠️ no-nesting Avoid nested then() or catch() statements
⚠️ no-promise-in-callback Avoid using promises inside of callbacks
⚠️ no-callback-in-promise Avoid calling cb() inside of a then() (use nodeify instead)
⚠️ avoid-new Avoid creating new promises outside of utility libs (use pify instead)
⚠️ no-return-in-finally Disallow return statements in finally()
⚠️ valid-params Ensures the proper number of arguments are passed to Promise functions
7️⃣ prefer-await-to-then Prefer await to then() for reading Promise values
7️⃣ prefer-await-to-callbacks Prefer async/await to the callback pattern

Key

icon description
‼️ Reports as error in recommended configuration
⚠️ Reports as warning in recommended configuration
7️⃣ ES2017 Async Await rules

catch-or-return

Ensure that each time a then() is applied to a promise, a catch() is applied as well. Exceptions are made if you are returning that promise.

Valid

myPromise.then(doSomething).catch(errors);
myPromise.then(doSomething).then(doSomethingElse).catch(errors);
function doSomethingElse() { return myPromise.then(doSomething) }

Invalid

myPromise.then(doSomething);
myPromise.then(doSomething, catchErrors); // catch() may be a little better
function doSomethingElse() { myPromise.then(doSomething) }

Options

allowThen

You can pass an { allowThen: true } as an option to this rule to allow for .then(null, fn) to be used instead of catch() at the end of the promise chain.

terminationMethod

You can pass a { terminationMethod: 'done' } as an option to this rule to require done() instead of catch() at the end of the promise chain. This is useful for many non-standard Promise implementations.

You can also pass an array of methods such as { terminationMethod: ['catch', 'asCallback', 'finally'] }.

This will allow any of

Promise.resolve(1).then(() => { throw new Error('oops') }).catch(logerror)
Promise.resolve(1).then(() => { throw new Error('oops') }).asCallback(cb)
Promise.resolve(1).then(() => { throw new Error('oops') }).finally(cleanUp)

no-return-wrap

Ensure that inside a then() or a catch() we always return or throw a raw value instead of wrapping in Promise.resolve or Promise.reject

Valid

myPromise.then(function(val) {
  return val * 2;
});
myPromise.then(function(val) {
  throw "bad thing";
});

Invalid

myPromise.then(function(val) {
  return Promise.resolve(val * 2);
});
myPromise.then(function(val) {
  return Promise.reject("bad thing");
})

Options

allowReject

Pass { allowReject: true } as an option to this rule to permit wrapping returned values with Promise.reject, such as when you would use it as another way to reject the promise.

param-names

Enforce standard parameter names for Promise constructors

Valid

new Promise(function (resolve) { ... })
new Promise(function (resolve, reject) { ... })

Invalid

new Promise(function (reject, resolve) { ... }) // incorrect order
new Promise(function (ok, fail) { ... }) // non-standard parameter names

Ensures that new Promise() is instantiated with the parameter names resolve, reject to avoid confusion with order such as reject, resolve. The Promise constructor uses the RevealingConstructor pattern. Using the same parameter names as the language specification makes code more uniform and easier to understand.

always-return

Ensure that inside a then() you make sure to return a new promise or value. See http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html (rule #5) for more info on why that's a good idea.

We also allow someone to throw inside a then() which is essentially the same as return Promise.reject().

Valid

myPromise.then((val) => val * 2));
myPromise.then(function(val) { return val * 2; });
myPromise.then(doSomething); // could be either
myPromise.then((b) => { if (b) { return "yes" } else { return "no" } });

Invalid

myPromise.then(function(val) {});
myPromise.then(() => { doSomething(); });
myPromise.then((b) => { if (b) { return "yes" } else { forgotToReturn(); } });

no-native

Ensure that Promise is included fresh in each file instead of relying on the existence of a native promise implementation. Helpful if you want to use bluebird or if you don't intend to use an ES6 Promise shim.

Valid

var Promise = require("bluebird");
var x = Promise.resolve("good");

Invalid

var x = Promise.resolve("bad");

no-nesting

Avoid nested then() or catch() statements

no-promise-in-callback

Avoid using promises inside of callbacks

no-callback-in-promise

Avoid calling cb() inside of a then() (use nodeify instead)

avoid-new

Avoid creating new promises outside of utility libs (use pify instead)

no-return-in-finally

Disallow return statements inside a callback passed to finally(), since nothing would consume what's returned.

Valid

myPromise.finally(function(val) {
  console.log('value:', val);
});

Invalid

myPromise.finally(function(val) {
  return val;
})

valid-params

Ensures the proper number of arguments are passed to Promise functions

Valid

// Promise.all() requires 1 argument
Promise.all([p1, p2, p3])
Promise.all(iterable)

// Promise.race() requires 1 argument
Promise.race([p1, p2, p3])
Promise.race(iterable)

// Promise.resolve() requires 0 or 1 arguments
Promise.resolve()
Promise.resolve({})
Promise.resolve([1, 2, 3])
Promise.resolve(referenceToObject)

// Promise.reject() requires 0 or 1 arguments
Promise.reject()
Promise.reject(Error())
Promise.reject(referenceToError)

// Promise.then() requires 1 or 2 arguments
somePromise().then(value => doSomething(value))
somePromise().then(successCallback, errorCallback)

// Promise.catch() requires 1 argument
somePromise().catch(error => { handleError(error) })
somePromise().catch(console.error)

// Promise.finally() requires 1 argument
somePromise().finally(() => { console.log('done!') })
somePromise().finally(console.log)

Invalid

  • Promise.all() is called with 0 or 2+ arguments
  • Promise.race() is called with 0 or 2+ arguments
  • Promise.resolve() is called with 2+ arguments
  • Promise.reject() is called with 2+ arguments
  • Promise.then() is called with 0 or 3+ arguments
  • Promise.catch() is called with 0 or 2+ arguments
  • Promise.finally() is called with 0 or 2+ arguments

prefer-await-to-then

Prefer await to then() for reading Promise values

prefer-await-to-callbacks

Prefer async/await to the callback pattern

Maintainers

License