1 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用 go 例程可以
執(zhí)行并發(fā)代碼。在您的示例中,您希望在返回時(shí)獲取響應(yīng)。執(zhí)行此操作的一種方法是使用通道。
您可以通過(guò)將一個(gè)通道傳遞給兩個(gè)函數(shù)來(lái)做到這一點(diǎn),其中一個(gè)生成數(shù)據(jù),另一個(gè)函數(shù)使用數(shù)據(jù)。這里有一篇關(guān)于頻道的很棒的文章。它看起來(lái)像這樣(注意我在這里使用了interface{}類型,如果你得到了一個(gè)具體的類型,它是更可取的方式)
func (s *server) MyEndpoint(ctx context.Context, request *MyRequest) (MyResponse, error) {
// other logic
// async
c := make(chan interface{})
go sendEmail(c)
// end async
// other logic - should not wait for the response from sendEmail
// getMyResponse must happen only after sendEmail has done
return getMyResponse(c), nil
}
- 1 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)