Golang Defer implement in Javascript
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.github
test
.all-contributorsrc
.editorconfig
.gitattributes
.gitignore
.gpmrc
.npmignore
.travis.yml
LICENSE
README.md
contributing.md
index.js
package.json
utils.js
yarn.lock

README.md

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