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();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Output
hello bob
failed
1
2
2
# 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)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Output
hello bob
failed
1
2
2
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22