0.4.0 • Published 8 years ago

godefer v0.4.0

Weekly downloads
1
License
Apache
Repository
github
Last release
8 years ago

Golang Defer implement in Javascript

Greenkeeper badge Build Status Coverage Status Dependency License Prettier Node npm version Size

Apply

You can use defer to do some job. e.g

  • Destroy resource
  • Auto Commit or Rollback in Transaction

Usage

const godefer = require('godefer');
const db = require('./db');

const getUserInfo = godefer(async function(username, defer) {
  const client = await db.createConnection();

  defer(function(err, result) {
    client.close(); // close connection after job done
  });

  const data = await client.query({ username });

  return data;
});

getUserInfo('axetroy')
  .then(function(info) {
    console.log(info);
  })
  .catch(function(err) {
    console.error(err);
  });

And here is the Golang code doing same with above

func getUserInfo(username string) (*User, error) {
  client, err := db.CreateConnection()
  if (err != nil) {
    return nil, err
  }

  defer func() {
    client.Close() // close connection after job done
  }()

  data := client.Qeury(map[string]interface{}{
    "username": username,
  })

  return &data, nil
}

func main() {
  if user, err := getUserInfo("axetroy"); err != nil {
    panic(err)
  }
  fmt.Println(user)
}

API

godefer(func:Function):deferFunction

  • func: It can be a common function or async function
  • deferFunction: It's a function wrap with func, the last argument must be defer

defer(cb:(err: Error|null, result:any)=>void):void

The defer task will run from the latest, Like Golang

Contributing

Contributing Guide

如果你觉得项目不错,不要吝啬你的 star.

长期造轮子,欢迎 follow.

Contributors

Axetroy💻 🐛 🎨

License

FOSSA Status

0.4.0

8 years ago

0.3.0

8 years ago

0.2.1

8 years ago

0.2.0

8 years ago

0.1.1

8 years ago

0.1.0

8 years ago