Turn any callback into promise
Basic promisify using leading comments
ES7 Async/Await + Arrow functions
via NPM
npm install babel-plugin-promise --save-dev
via YARN
yarn add babel-plugin-promise --dev
before
var fs = require("fs");
//@promisify<err,data> promiseName
__ = fs.readFile("../package.json", "utf8");
after
var fs = require("fs");
//@promisify<err,data> promiseName
function promiseName() {
return new Promise((resolve, reject) => {
fs.readFile("../package.json", "utf8", (err, data) => {
if (err) reject(err);
resolve(data);
});
});
}
promiseName().then(res => {
console.log(res);
});
If the callback does not return us the error message, insert null
instead of error
before
var fs = require("fs");
//@promisify<null,data> promiseName
__ = fs.readFile("../package.json", "utf8");
after
var fs = require("fs");
//@promisify<null,data> promiseName
function promiseName() {
return new Promise(resolve => {
fs.readFile("../package.json", "utf8", data => {
resolve(data);
});
});
}
You can see that it does not handle reject
For custom arguments
before
//@promisify<err,data> findUser
__ = User.findOne(arg1);
after
//@promisify<err,data> findUser
function findUser(arg1) {
return new Promise((resolve, reject) => {
User.findOne(arg1, (err, data) => {
if (err) reject(err);
resolve(data);
});
});
}
This time you should use trailing comments
before
var fs = require("fs");
async function someFunction(){
await fs.readFile('./package.json','utf8') //@promisify<err,data>
}
after
var fs = require("fs");
async function someFunction() {
await new Promise((resolve, reject) => {
fs.readFile('./package.json', 'utf8', (err, data) => {
if (err) reject(err);
resolve(data);
});
}); //@promisify<err,data>
}
Also, you can make promises with an arrow function expression
before
var fs = require("fs");
const some = async () => await fs.readFile("./package.json", "uft8"); //@promisify<err,data>
after
var fs = require("fs");
const some = async () => await new Promise((resolve, reject) => {
fs.readFile("./package.json", "uft8", (err, data) => {
if (err) reject(err);
resolve(data);
});
}); //@promisify<err,data>