Skip to content

Latest commit

 

History

History
 
 

plugin-promises

@putout/plugin-promises NPM version

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

(c) MDN

🐊Putout plugin adds ability to work with promises.

Install

npm i @putout/plugin-promises -D

Rule

{
    "rules": {
        "promises/add-missing-await": "on",
        "promises/apply-await-import": "on",
        "promises/apply-top-level-await": "on",
        "promises/remove-useless-resolve": "on",
        "promises/remove-useless-async": "on",
        "promises/remove-useless-await": "on",
        "promises/convert-reject-to-throw": "on",
        "promises/convert-new-promise-to-async": "on"
    }
}

apply-await-import

add forgotten await to dynamic import().

❌ Example of incorrect code

const {readFile} = import('fs/promises');

✅ Example of correct code

const {readFile} = await import('fs/promises');

remove-useless-resolve

❌ Example of incorrect code

async function hello() {
    return Promise.resolve('hello');
}

✅ Example of correct code

async function hello() {
    return 'hello';
}

remove-useless-async

❌ Example of incorrect code

async function hello() {
    return 'hello';
}

✅ Example of correct code

function hello() {
    return 'hello';
}

remove-useless-await

If a handler function returns another pending promise object, the resolution of the promise returned by then will be subsequent to the resolution of the promise returned by the handler. Also, the resolved value of the promise returned by then will be the same as the resolved value of the promise returned by the handler.

(c) MDN

❌ Example of incorrect code

await await Promise.resolve();
const hello = await 'world';

✅ Example of correct code

await Promise.resolve();
const hello = 'world';

convert-reject-to-throw

❌ Example of incorrect code

async function hello() {
    return Promise.reject(Error('error'));
}

✅ Example of correct code

async function hello() {
    throw Error('error');
}

add-missing-await

❌ Example of incorrect code

runCli();

async function runCli() {
}

✅ Example of correct code

await runCli();

async function runCli() {
}

convert-new-promise-to-async

❌ Example of incorrect code

function get() {
    return new Promise((resolve, reject) => {
        reject(Error('Cannot get'));
    });
}

✅ Example of correct code

async function get() {
    throw Error('Cannot get');
}

apply-top-level-await

Applies top-level-await.

❌ Example of incorrect code

import {readFile} from 'fs/promises';

(async () => {
    await readFile('./README.md', 'utf8');
})();

✅ Example of correct code

import {readFile} from 'fs/promises';

await readFile('./README.md', 'utf8');

License

MIT