Moj*_*imi 7 javascript ajax dojo asynchronous
有一个异步调用我正在查询服务上的数据库,但是这个服务有一个限制,它可以一次输出多少,所以我需要检查它是否通过它发送的结果达到其限制并重复查询直到没有.
同步样机:
var query_results = [];
var limit_hit = true; #While this is true means that the query hit the record limit
var start_from = 0; #Pagination parameter
while (limit_hit) {
    Server.Query(params={start_from : start_from}, callback=function(result){
        limit_hit = result.limit_hit;
        start_from = result.results.length;
        query_result.push(result.results);
    }
}
显然上面的内容不起作用,我在这里看到了一些关于这个问题的其他问题,但他们没有提到当你需要每次迭代等待最后一次完成时你该怎么做而你之前不知道迭代次数.
我怎样才能打开上面的异步?我愿意接受使用promise/deferred-like逻辑的答案,但最好是干净利落的东西.
我大概能想到这样使用等待/超时的monstruous和可怕的方式,但必须有解决它干净,聪明的和现代的方式.
另一种方法是做一个"预查询"以了解事前的特征数量,这样你就知道循环的数量,我不确定这是否是正确的方法.
这里我们有时会使用Dojo,但是我发现的例子并没有解释当你有一个未知数量的循环时该怎么做https://www.sitepen.com/blog/2015/06/10/dojo-faq-how-can -i-序列异步的操作/
If you want to use a loop then I think there is no (clean) way to do it without Promises.
A different approach would be the following:
var query_results = [];
var start_from = 0;
funciton myCallback(result) {  
  if(!result) {
    //first call
    Server.Query({ start_from: start_from}, myCallback);
  } else {
    //repeated call
    start_from = result.results.length
    query_result.push(result.results);
    
    if(!result.limit_hit) {
      //limit has not been hit yet
      //repeat the query with new start value
      Server.Query({ start_from: start_from}, myCallback);
    } else {
        //call some callback function here
    }
  }
}
myCallback(null);You could call this recursive, but since the Query is asynchronous you shouldn't have problems with call stack limits etc.
Using promises in an ES6 environment you could make use of async/await. Im not sure if this is possible with dojo.
| 归档时间: | 
 | 
| 查看次数: | 214 次 | 
| 最近记录: |