编写轮询方法(使用Typescript和AngularJS)的最佳(右)方法是什么?

d-_*_*_-b 4 javascript ajax angularjs typescript

我正在尝试编写一个轮询方法,定期轮询服务器以检查是否已创建zip文件.

我想要完成的是以下内容:

  1. 调用(ajax)一个在服务器上创建zip文件的API
  2. 调用(ajax)另一个API来检查是否已经创建了zip文件(轮询方法)
  3. 一些后续过程

这是我的代码片段↓

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...
         });
       }
});
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供一些在这种情况下可行的轮询方法示例吗?

添加:

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;          
        }
Run Code Online (Sandbox Code Playgroud)

bas*_*rat 5

基本上抽象出方法如下所示:

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*/));
Run Code Online (Sandbox Code Playgroud)

更新

根据以下评论的要求:

返回此.$ timeout(继续,1000);

这需要角度来启动摘要周期.