godefer

Golang Defer implement in Javascript

APACHE-2.0 License

Downloads
335
Stars
18

Golang Defer implement in Javascript

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

Package Rankings
Top 12.28% on Npmjs.org
Badges
Extracted from project README
Build Status Coverage Status Dependency Prettier npm version FOSSA Status