What is the best (correct) way to write a polling method (using Typescript & AngularJS)?

I am trying to write a polling method that periodically checks the server to see if a zip file has already been created or not.

I want to do the following:

  • Calls (ajax) the API that creates the zip file on the server
  • Calls (ajax) another API that checks if a zip file has already been created (polling method)
  • Next process

Here is my code snippet ↓

var success: boolean = false;
//1. requests a server to create a zip file
this.apiRequest.downloadRequest(params,ApiUrl.URL_FOR_DOWNLOAD_REQUEST)
.then((resObj) => {
       var apiRes: IDownloadService = resObj.data;
       if (apiRes.status[0].statusCode == "000") {
            success = true;
       } else {
            //Error
       }
}).then(() => {
       if (success) {
         //2. polls the server to check if the zip file is ready
         <- Polling method↓ ->
         this.polling(params).then((zipUrl) => {
                    console.log(zipUrl); //always logs zipUrl
                    //some subsequent process...
         });
       }
});

Can someone give examples of survey methods that will work in this case?

Added:

private polling(params: any): ng.IPromise<any> {
            var poller = () => this.apiRequest.polling(params, ApiUrl.URL_FOR_POLLING);
            var continuation = () => poller().then((resObj) => {
                var apiRes: IDownloadService = resObj.data;
                if (apiRes.zipFilePath == "") {
                    return this.$timeout(continuation, 1000);
                } else {
                    return apiRes.zipFilePath;
                }
            })
            var result: ng.IPromise<any> = continuation();
            return result;          
        }
+4
source share
1 answer

Basically abstract the methods as shown below:

let poll = () => this.apiRequest.downloadRequest(params,ApiUrl.URL_FOR_DOWNLOAD_REQUEST)

let continuation = () => poll().then((/*something*/)=> {
 /*if still bad*/ return continuation();
 /*else */ return good;
})

continuation().then((/*definitely good*/));

Update

As indicated in the comment below:

return this. $timeout (, 1000);

, angular, .

+4

All Articles