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
当前内容版权归 miguelmota 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 miguelmota .