A decorator for ES7, useful to improve readability of methods which returning a promise.
Promisifier is a part of the Pigalle framework.
- NodeJS >= 5.7.0
npm install pigalle-decorator-promisifier
Instead of writing a method that returns a promise :
class Clazz {
divide(a, b) {
return new Promise((resolve, reject) => {
if (b === 0) {
reject(new Error());
} else {
resolve(a/b);
}
});
}
}
... write a method decorated with @promisifier
:
import promisifier from 'pigalle-decorator-promisifier';
class Clazz {
@promisifier
divide(a, b, resolve, reject) {
if (b === 0) {
reject(new Error());
} else {
resolve(a/b);
}
}
}
You can also simplify the source code using return
and throw
:
import promisifier from 'pigalle-decorator-promisifier';
class Clazz {
@promisifier
divide(a, b) {
if (b === 0) {
throw new Error('division by zero!');
} else {
return a/b;
}
}
}
At runtime, @promisifier
transforms the method and returns a promise that you can use as you wish:
const clazz = new Clazz();
clazz.divide(5, 0).then((result) => {
console.log(result);
}).catch((err) => {
throw err;
});
npm test
npm install
gulp babel
git clone git@github.com:9fevrier/pigalle-decorator-promisifier
cd pigalle-decorator-promisifier
npm install
gulp watch
- Fix bug: resolve is undefined.
- Fix bug: call an attribute of current instance (
this
) returnsundefined
.
- Initial version including the
@promisifier
decorator for EcmaScript7.
The MIT License (MIT)
Copyright (c) 2016 9 Février <contact@9fevrier.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.