0

我在我的网站上启用了 WCF-Ajax。

我需要异步保存文件,但最后我需要知道所有异步操作何时完成。

function test()
{
   for (var i = 0; i < arr.length; i++) {
         saveFileService.SaveFile(arr[i], onSaveFileComplete);
   }

   //TODO: CHECK THAT **ALL** FILE SAVES ARE DONE  
}

function onSaveFileComplete(result)
{
  // ONE FILE SAVE ENDED SUCCESSFULLY
}

如何编写“TODO”部分?

4

3 回答 3

2

保存文件时只需使用全局计数器...

var fiesCurrentlySaving = 0;

function test()
{
   for (var i = 0; i < arr.length; i++) {
         // Increase counter for the number of files saving
         filesCurrentlySaving++;

         // Save the file
         saveFileService.SaveFile(arr[i], onSaveFileComplete);
   }
}

function onSaveFileComplete(result)
{
    // Reduce the file counter
    filesCurrentlySaving--;

    if (filesCurrentlySaving <= 0)
    {
        // Do whatever you need to do now!
    }
}
于 2013-06-04T08:55:21.057 回答
1

您可以维护一个计数器变量并在完成回调中增加它。当它到达时arr.length,所有文件都将被处理。

就像是:

function test()
{
    var processedFiles = 0, fileCount = arr.length;
    for (var i = 0; i < fileCount; i++) {
        saveFileService.SaveFile(arr[i], function() {
            // One file save ended successfully.
            if (++processedFiles == fileCount) {
                // All files have been processed.
            }
        });
    }
}
于 2013-06-04T08:54:52.680 回答
0

试试这个

function test()
{
   for (var i = 0; i < arr.length; i++) {
 saveFileService.SaveFile(arr[i], onSaveFileComplete);
     if(i == arr.length)
     {
       //TODO: CHECK THAT **ALL** FILE SAVES ARE DONE 
     }   
}
}
于 2013-06-04T08:59:51.667 回答