|
|
|
|
|
by 4bpp
2219 days ago
|
|
Isn't there still a key difference there? Inserting the latter snippet in your Golang function does not require you to change anything about the function's definition or calling conventions. From the outside, it continues looking and behaving exactly as any other (synchronous) Golang function. On the other hand, if your JS function contains an await, then it must be made async and every invocation of it must be made prefixed with await or some other async-wrangling boilerplate, you lose access to language features such as exceptions et cetera. Golang functions only have one colour. This colour may be closer to "red" than "blue", but at least you never need to concern yourself with this as the consumer of an API, and you can count on the rest of the language having been designed around what is possible with these "purple" functions, as opposed to JS where the situation is that the language provides you with plenty of nice features to structure your code on paper but the design of existing code you need to interface with prevents you from effectively using them. |
|
Neither does the C# snippet. In fact, if you want to extract the result of the function call as well, you can still keep you API as is in C#, and use Task.wait() or something similar to block execution until the task is finished, and read its result.
In Go there is no such alternative: if you have a value-returning function, and want to run it asynchronously and continue when the value is available, you have to re-write the function into a void function and add as many channel parameters as return values it held (or wrap the original function with something which calls it synchronously and then pushes those values on the channels),or use some shared memory to store the results. And make sure to also catch any panics the function might raise, if you were planning to handle panics.
I would not be surprised if some future version of Go introduces async/await to handle all of this complexity for you, except that Go developers usually hate making things easier for their users.
Edit to add: channels in Go actually tend to impose colors on functions just as much as async/await in C#. You can't call a function which returns its result in a channel synchronously, you must start it in a separate goroutine. Unfortunately, the compiler doesn't know this and will let you create a silly deadlock that way.