Golang Defer implement in Javascript
APACHE-2.0 License
You can use defer to do some job. e.g
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)
}
func
, the last argument must be defer
The defer task will run from the latest, Like Golang
如果你觉得项目不错,不要吝啬你的 star.
长期造轮子,欢迎 follow.
Axetroy💻 🐛 🎨 |
---|