[英]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: 这里有两个问题:
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.