edit-icon download-icon

Asynchronous calls

Last Updated: Mar 20, 2018

Initiate asynchronous calls

Note the following before making asynchronous calls:

  • Because of the concurrent characteristic of the Go language, we recommend that you control the concurrent requests of SDK on the application layer.

  • To facilitate your usage, Alibaba Cloud Go SDK provides the concurrent calling method that can be directly used. The related concurrency control is achieved within SDK.

Enable the concurrent feature for SDK Client

In the following example, the Credential object is used to set up user credentials.

  1. // The maximum number of concurrent connections
  2. poolSize := 10
  3. // The maximum number of cacheable requests
  4. maxTaskQueueSize := 10000
  5. // Enable the asynchronous feature when creating a client
  6. config := sdk.NewConfig().
  7. WithEnableAsync(true).
  8. WithGoRoutinePoolSize(poolSize). // Optional, the default value is 5
  9. WithMaxTaskQueueSize(maxTaskQueueSize) // Optional, the default value si 1,000
  10. // Use the custom configuration to initiate the client
  11. ecsClient, err := ecs.NewClientWithOptions("<your-region-id>", config, credential)
  12. // Or enable the asynchronous feature after initiating the client
  13. client.EnableAsync(poolSize, maxTaskQueueSize)

Initiate asynchronous calls

You can make asynchronous calls using the following two methods:

  • Use channel as the return value

    1. // this will not block
    2. responseChannel, errChannel := client.FooWithChan(request)
    3. // this will block
    4. response := <-responseChannel
    5. err = <-errChannel
  • Use callbacks

    1. // this will not block
    2. blocker := client.FooWithCallback(request, func(response *FooResponse, err error) {
    3. // handle the response and err
    4. })
    5. // The blocker is (chan int) and is used for controlling synchronization. The action succeeds when the return value is one, and fails when the return value is zero.
    6. // When <-blocker returns zero and the action fails, the error is transmitted to callback through err.
    7. // this will block
    8. result := <-blocker
Thank you! We've received your feedback.