Skip to content
master
Switch branches/tags
Go to file
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

babel-plugin-promise

Travis

Turn any callback into promise

Basic promisify using leading comments

Without error handling.

Using your own arguments

ES7 Async/Await

ES7 Async/Await + Arrow functions

via NPM

npm install babel-plugin-promise --save-dev

via YARN

yarn add babel-plugin-promise --dev

Basic

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);
});

Without error handling.

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

Using your own arguments

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);
    });
  });
}

ES7 Async/Await

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>
}

ES7 Async/Await + Arrow functions

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>