async/await

async/await


Node.js

function hello(name) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (name === 'fail') {
        reject(new Error('failed'))
      } else {
        resolve('hello ' + name)
      }
    }, 1e3)
  })
}

async function main() {
  try {
    let output = await hello('bob')
    console.log(output)

    output = await hello('fail')
    console.log(output)
  } catch(err) {
    console.log(err.message)
  }
}

main()

Output

hello bob
failed

Go

(closest thing is to use channels)

package main

import (
    "errors"
    "fmt"
    "time"

    "github.com/prometheus/common/log"
)

func hello(name string) chan interface{} {
    ch := make(chan interface{}, 1)
    go func() {
        time.Sleep(1 * time.Second)
        if name == "fail" {
            ch <- errors.New("failed")
        } else {
            ch <- "hello " + name
        }
    }()

    return ch
}

func main() {
    result := <-hello("bob")
    switch v := result.(type) {
    case string:
        fmt.Println(v)
    case error:
        log.Errorln(v)
    }

    result = <-hello("fail")
    switch v := result.(type) {
    case string:
        fmt.Println(v)
    case error:
        log.Errorln(v)
    }
}

Output

hello bob
failed