简体   繁体   English

递归自调用函数和异步操作

[英]Recursive self-invoked function and asynchronous operations

From this question , I gathered that I could use either a forEach loop or a self-invoked to perform asynchronous I/O operations. 这个问题中 ,我得出结论,我可以使用forEach循环或自调用来执行异步I / O操作。 I'm not sure why it isn't working for me, but the loop part of things work properly without any asynchronous function being called. 我不确定为什么它对我不起作用,但是事情的循环部分可以正常工作而无需调用任何异步函数。

var fileNames = ["fileA", "fileB", "fileC", "fileD", "fileE", "fileF", "fileG", "fileH"];
var json;

(function parseFiles(i) {

    console.log(i + " " + fileNames[i]);

    var uri = new Windows.Foundation.Uri('ms-appx:///data/' + fileNames[i] + '.json');

    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(function (file) {
        Windows.Storage.FileIO.readTextAsync(file).then(function (contents) {
            json[fileNames[i]] = JSON.parse(contents);

            if (i < fileNames.length) {
                parseFiles(i+1);
            } else {}
        });
    });

})(0);

My console output is kind of strange: 我的控制台输出有点奇怪:

0 fileA
1 fileB
0 fileA
2 fileC
1 fileB
3 fileD
2 fileC
3 fileD

Two questions here: 这里有两个问题:

  1. How do I fix it so that it goes from fileA to fileH? 如何解决它,使其从fileA到fileH?
  2. After parsing the files, do I put the code to work with the variable json after the self-invoked function or in the else loop in the then function of the Promise returned by readFileAsync() ? 解析完文件后,我应将代码与自调用函数之后的变量json一起使用,还是放在readFileAsync()返回的Promise的then函数的else循环中?

I ended up doing this: 我最终这样做:

var fileNames = ["fileA", "fileB", "fileC", "fileD", "fileE", "fileF", "fileG", "fileH"];
var json;

(function parseFiles() {

    var name = fileNames.pop();

    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(new Windows.Foundation.Uri('ms-appx:///data/' + name + '.json'))
        .then(function (file) {
            return Windows.Storage.FileIO.readTextAsync(file);
        }, function error(e){
            console.dir(e);
        })
        .then(function (contents) {
            json[name] = JSON.parse(contents);
        })
        .then(function () {
            console.log("Name: "+name+" Remaining array length:"+fileNames.length);

            if (fileNames.length === 0) {
                console.log('all done');
                // do whatever else here
            } else {
                parseFiles();
            }
        });
})();

I'm just glad that the asynchronous methods in the recursive function use the Promise interface so I don't have to write a whole bunch of recursive functions. 我很高兴递归函数中的异步方法使用Promise接口,因此我不必编写一堆递归函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在自调用的jquery函数中获取php值? - how get a php value inside a self-invoked jquery function? 如何将这个命名的自调用函数传递给参数? - How is this named self-invoked function being passed an argument? 为什么这个JS自调用函数不起作用? - Why doesn't this JS self-invoked function work? 为什么函数在对象文字中被自动调用? - Why is a function being self-invoked within an object literal? 在自调用 function 末尾有括号或在 javascript 中没有括号有什么区别? - what is the difference between has parentheses at the end of self-invoked function or has not in the javascript? NodeJS:在对象中创建条件属性的方法比自调用函数更短? (ES5或ES6) - NodeJS: shorter way to create a conditional property in an object than self-invoked function? (either ES5 or ES6) 当前代码需要是 IIFE(自调用) - 代码工作并运行 - Current code needs to be IIFE(Self-Invoked) - Code works and runs 比较预先声明和自调用的匿名函数 - Comparing Pre-declared and Self-invoked Anonymous Functions 将“严格模式”包装在IIFE(自调用)表达式中是否是一种好习惯? - Is it a good practice to wrap “strict mode” inside an IIFE (self-invoked) expression? 自我调用的Javascript函数 - Self invoked Javascript function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM