promise/no-return-wrap Style ​
What it does ​
Prevents unnecessary wrapping of return values in promises with either Promise.resolve
or Promise.reject
.
This rule enforces the following stances:
When a promise is to be resolved, instead of returning
Promise.resolve(value)
it is better to return the raw value withreturn value
instead.When a promise is to be rejected, instead of returning
Promise.reject(error)
, instead the raw error value should be thrown as inthrow error
.
There is an option to turn off the enforcing of 2, see the options section below.
Why is this bad? ​
It is unnecessary to use Promise.resolve
and Promise.rejectfor converting raw values to promises in the return statements of
thenand
catchcallbacks. Using these operations to convert raw values to promises is unnecessary as simply returning the raw value for the success case and throwing the raw error value in the failure case have the same effect. This is why some take the opinion that returning values such as
Promise.resolve(1)or
Promise.reject(err)` is syntactic noise.
Examples ​
Examples of incorrect code for this rule:
myPromise().then(() => Promise.resolve(4));
myPromise().then(function () {
return Promise.resolve(4);
});
myPromise().then(() => Promise.reject("err"));
myPromise().then(function () {
return Promise.reject("err");
});
myPromise().catch(function () {
return Promise.reject("err");
});
myPromise().finally(function () {
return Promise.reject("err");
});
myPromise().finally(() => Promise.resolve(4));
Examples of correct code for this rule:
myPromise().then(() => 4);
myPromise().then(function () {
return 4;
});
myPromise().then(() => throw "err");
myPromise().then(function () {
throw "err";
});
myPromise().catch(function () {
throw "err";
});
myPromise().finally(() => 4);
Options ​
allowReject ​
{ type: boolean, default: false }
The allowReject
turns off the checking of returning a call Promise.reject
inside a promise handler.
With allowReject
set to true
the following are examples of correct code:
myPromise().then(function () {
return Promise.reject(0);
});
myPromise()
.then()
.catch(() => Promise.reject("err"));
How to use ​
To enable this rule in the CLI or using the config file, you can use:
oxlint --deny promise/no-return-wrap --promise-plugin
{
"plugins": ["promise"],
"rules": {
"promise/no-return-wrap": "error"
}
}