人人能看懂的Async/Await 模式-Go

1,174 阅读1分钟

转发大佬使用 Go 实现 Async/Await 模式 - Golang发烧友的文章 - 知乎

package async

import "context"


type Future interface {

	Await() interface{}

}

type future struct {

	await func(ctx context.Context) interface{}

}

func (f future) Await() interface{} {

	return f.await(context.Background())

}

// Exec executes the async function

func Exec(f func() interface{}) Future {

	var result interface{}

	c := make(chan struct{})

	go func() {

		defer close(c)

		result = f()

	}()

	return future{

		await: func(ctx context.Context) interface{} {

			select {

			case <-ctx.Done():

				return ctx.Err()

			case <-c:

				return result

			}

		},

	}

}



func DoneAsync() int {

	fmt.Println("Warming up ...")

	time.Sleep(3 * time.Second)

	fmt.Println("Done ...")

	return 1

}

func main() {

	fmt.Println("Let's start ...")

	future := async.Exec(func() interface{} {

		return DoneAsync()

	})

	fmt.Println("Done is running ...")

	val := future.Await()

	fmt.Println(val)

}