Skip to content

Commit e544cc9

Browse files
committed
Optimizing network.go
1 parent ff1e559 commit e544cc9

File tree

1 file changed

+29
-23
lines changed

1 file changed

+29
-23
lines changed

cmd/network.go

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -135,32 +135,38 @@ func getResponseData(data map[string]interface{}) map[string]interface{} {
135135
}
136136

137137
func pollAsyncJob(r *Request, jobID string) (map[string]interface{}, error) {
138-
for timeout := float64(r.Config.Core.Timeout); timeout > 0.0; {
139-
startTime := time.Now()
140-
spinner := r.Config.StartSpinner("polling for async API result")
141-
queryResult, queryError := NewAPIRequest(r, "queryAsyncJobResult", []string{"jobid=" + jobID}, false)
142-
diff := time.Duration(1*time.Second).Nanoseconds() - time.Now().Sub(startTime).Nanoseconds()
143-
if diff > 0 {
144-
time.Sleep(time.Duration(diff) * time.Nanosecond)
145-
}
146-
timeout = timeout - time.Now().Sub(startTime).Seconds()
147-
r.Config.StopSpinner(spinner)
148-
if queryError != nil {
149-
return queryResult, queryError
150-
}
151-
jobStatus := queryResult["jobstatus"].(float64)
152-
if jobStatus == 0 {
153-
continue
154-
}
155-
if jobStatus == 1 {
156-
return queryResult["jobresult"].(map[string]interface{}), nil
138+
timeout := time.NewTimer(time.Duration(float64(r.Config.Core.Timeout)) * time.Second)
139+
ticker := time.NewTicker(time.Duration(2 * time.Second))
140+
defer ticker.Stop()
141+
defer timeout.Stop()
157142

158-
}
159-
if jobStatus == 2 {
160-
return queryResult, errors.New("async API failed for job " + jobID)
143+
spinner := r.Config.StartSpinner("polling for async API result")
144+
defer r.Config.StopSpinner(spinner)
145+
146+
for {
147+
select {
148+
case <-timeout.C:
149+
return nil, errors.New("async API job query timed out")
150+
151+
case <-ticker.C:
152+
queryResult, queryError := NewAPIRequest(r, "queryAsyncJobResult", []string{"jobid=" + jobID}, false)
153+
if queryError != nil {
154+
return queryResult, queryError
155+
}
156+
jobStatus := queryResult["jobstatus"].(float64)
157+
158+
switch jobStatus {
159+
case 0:
160+
continue
161+
162+
case 1:
163+
return queryResult["jobresult"].(map[string]interface{}), nil
164+
165+
case 2:
166+
return queryResult, errors.New("async API failed for job " + jobID)
167+
}
161168
}
162169
}
163-
return nil, errors.New("async API job query timed out")
164170
}
165171

166172
// NewAPIRequest makes an API request to configured management server

0 commit comments

Comments
 (0)