node.js - Does Go have callback concept? -
i found many talks saying node.js bad because of callback hell , go because of synchronous model.
what feel go can callback same node.js in synchronous way. can pass anonymous function , closure things
so, why comparing go , node.js in callback perspective if go cannot become callback hell.
or misunderstand meaning of callback , anonymous function in go?
a lot of things take time, e.g. waiting on network socket, file system read, system call, etc. therefore, lot of languages, or more precisely standard library, include asynchronous version of functions (often in addition synchronous version), program able else in mean-time.
in node.js things more extreme. use single-threaded event loop , therefore need ensure program never blocks. have written standard library built around concept of being asynchronous , use callbacks in order notify when ready. code looks this:
dosomething1(arg1, arg2, function() { dosomething2(arg1, arg2, function() { dosomething3(function() { // done }); }); }); somethingelse();
dosomething1
might take long time execute (because needs read network example), program can still execute somethingelse
in mean time. after dosomething1
has been executed, want call dosomething2
, dosomething3
.
go on other hand based around concept of goroutines , channels (google "communicating sequential processes", if want learn more abstract concept). goroutines cheap (you can have several thousands of them running @ same time) , therefore can use them everywhere. same code might in go:
go func() { dosomething1(arg1, arg2) dosomething2(arg1, arg2) dosomething3() // done }() somethingelse()
whereas node.js focus on providing asynchronous apis, go encourages write synchronous apis (without callbacks or channels). call dosomething1
block current goroutine , dosomething2
executed after dosomething1
has finished. that's not problem in go, since there other goroutines available can scheduled run on system thread. in case, somethingelse
part of goroutine , can executed in meantime, in node.js example.
i prefer go code, since it's easier read , reason about. advantage of go works computation heavy tasks. if start heavy computation in node.js doesn't need wait network of filesystem calls, computation blocks event loop. go's scheduler on other hand best dispatch goroutines on few number of system threads , os might run threads in parallel if cpu supports it.
Comments
Post a Comment