Callback Function -> Golang & NodeJS
Callback: Passing a Function as an Argument
GoLang Example
- Supper Example 1:
https://play.golang.org/p/AI8jKiYIKO6
- Supper Example 2:
package mainimport "fmt"func visit(numbers []int, callback func(int)) {for _, n := range numbers {callback(n)}}func main() {visit([]int{1, 2, 3, 4}, func(n int) {fmt.Println(n)})}// callback: passing a func as an argument
package main
import "fmt"
func filter(numbers []int, callback func(int) bool) []int {
var xs []int
for _, n := range numbers {
if callback(n) {
xs = append(xs, n)
}
}
return xs
}
func main() {
xs := filter([]int{1, 2, 3, 4}, func(n int) bool {
return n > 1
})
fmt.Println(xs) // [2 3 4]
}
package mainimport ("fmt")func main() {ii := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}s := sum(ii...)fmt.Println("all numbers", s)s2 := even(sum, ii...)fmt.Println("even numbers", s2)s3 := odd(sum, ii...)fmt.Println("odd numbers", s3)}func sum(xi ...int) int {total := 0for _, v := range xi {total += v}return total}func even(f func(xi ...int) int, vi ...int) int {var yi []intfor _, v := range vi {if v%2 == 0 {yi = append(yi, v)}}return f(yi...)}func odd(f func(xi ...int) int, vi ...int) int {var yi []intfor _, v := range vi {if v%2 != 0 {yi = append(yi, v)}}return f(yi...)}
NodeJS Example
var express = require('express'); var app = express(); var fs = require("fs"); var user = { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } app.post('/addUser', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); data["user4"] = user["user4"]; console.log( data ); res.end( JSON.stringify(data)); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port)
https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm
Comments
Post a Comment