如何实现一个windows store javascript应用的异步for循环

How to implement an Asynchronous for loop for a windows store javascript app?

本文关键字:应用 javascript 异步 循环 for store 一个 何实现 实现 windows      更新时间:2023-09-26

我目前正在开发一个windows store javascript应用程序,在实现异步for循环时遇到了困难。

考虑一个简单的for循环,如下所示

for(i=0,i<4,i++)
{
//body
}

可以执行与上面代码相同的过程的asyncFor循环是什么

使用回调函数

someFunction = function(data, ...){
    someAsyncFn(someFunction); //use this function as the callback
}

除非我理解正确…您可以尝试这样做:

function asyncFor(n, callback)
{
    var i=0;
    var t=setInterval(function(){
        callback();
        i++;
        if(i==n)
            clearInterval(t);
    }, 0);
}
asyncFor(4, function(){
    console.log('hello world');
});
console.log('after for'); 

如果没有-对不起,忽略我的回答

You can use a recursive function callback
 function test(){
  myCall(function(){
       alert("Hello world");
    },5);
 }
function myCall(callback , count){
      if(count === 0){
           return;
      }else{
         callback();
         count--;
      }
      myCall(callback , count);
}

通常,您需要递归地编写循环代码—从异步回调调用下一个递归步骤:

function loop(i, n, body, callback) {
    if (i < n)
        body(i, function cb() {
            loop(i+1, n, body, callback);
        });
    else
        callback();
}

然后像

一样使用
loop(0, 4, function(i, cb) {
    console.log(i);
    setTimeout(cb, 50); // or whatever async task with callback you have
}, function() {
    console.log("done everything");
});

如果要在数组上循环,这两个帮助器可能会派上用场(CoffeeScript语法可以提供更简洁的符号)。如果你不喜欢猴子补丁,可以自由地将它们转换为独立的函数。

# call function for each element in array
# returns when all promises have been completed
Array::eachAsync = (fn) ->
  promises = @map (item, index, collection) -> fn(item, index, collection)
  WinJS.Promise.join(promises)
# call function for each element in array in order
# returns when the last one has been processed
Array::sequentialEachAsync = (fn) ->
  @reduce (lastPromise, item) ->
    lastPromise.then () -> fn(item)
  , WinJS.Promise.wrap()