写一个轮询方法的最佳(正确)方式是什么?AngularJS)

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

本文关键字:正确 最佳 方式 AngularJS 是什么 一个 方法      更新时间:2023-09-26

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

我想完成的是:

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

这是我的代码片段↓

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...
         });
       }
});

谁能给出一些在这种情况下工作的轮询方法的例子?

补充道:

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;          
        }

将这些方法抽象出来,如下所示:

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*/));
<标题> 更新

按照下面评论的要求:

返回。美元超时(延续,1000);

这是需要的角开始消化循环