简体   繁体   中英

What's the best(right) way to write a polling method (with Typescript & AngularJS)?

I am trying to write a polling method that polls a server periodically to check whether a zip file has already been created or not.

What I want to accomplish are the following:

  1. Calls(ajax) an API that creates a zip file on server
  2. Calls(ajax) another API that checks if the zip file has already been created (polling method)
  3. Some subsequent 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...
         });
       }
});

Could anyone give some examples of polling method that would 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;          
        }

Basically abstract the methods out 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 requested in the comment below:

return this.$timeout(continuation, 1000);

This is needed to get angular to kick off a digest cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM