我在我的网站上启用了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”部分?
答案 0 :(得分: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!
}
}
答案 1 :(得分: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.
}
});
}
}
答案 2 :(得分: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
}
}
}