async/await


Node.js

  1. function hello(name) {
  2. return new Promise((resolve, reject) => {
  3. setTimeout(() => {
  4. if (name === 'fail') {
  5. reject(new Error('failed'))
  6. } else {
  7. resolve('hello ' + name)
  8. }
  9. }, 1e3)
  10. })
  11. }
  12. async function main() {
  13. try {
  14. let output = await hello('bob')
  15. console.log(output)
  16. output = await hello('fail')
  17. console.log(output)
  18. } catch(err) {
  19. console.log(err.message)
  20. }
  21. }
  22. main()

Output

  1. hello bob
  2. failed

Go

(closest thing is to use channels)

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "github.com/prometheus/common/log"
  7. )
  8. func hello(name string) chan interface{} {
  9. ch := make(chan interface{}, 1)
  10. go func() {
  11. time.Sleep(1 * time.Second)
  12. if name == "fail" {
  13. ch <- errors.New("failed")
  14. } else {
  15. ch <- "hello " + name
  16. }
  17. }()
  18. return ch
  19. }
  20. func main() {
  21. result := <-hello("bob")
  22. switch v := result.(type) {
  23. case string:
  24. fmt.Println(v)
  25. case error:
  26. log.Errorln(v)
  27. }
  28. result = <-hello("fail")
  29. switch v := result.(type) {
  30. case string:
  31. fmt.Println(v)
  32. case error:
  33. log.Errorln(v)
  34. }
  35. }

Output

  1. hello bob
  2. failed