[英]Windows 8 Javascript asynchronous programming
我想遍历列表并重命名Windows 8 / Javascript中的一些文件。 因此,我编写了一个名为“ renameFile”的函数,并在循环中调用了该函数,如下所示:
list.forEach(function (value, index, array) {
var filename = index;
var newfilename = index+1;
renameFile(filename, newfilename);
});
function renameFile(filename, newfilename) {
Windows.Storage.ApplicationData.current.localFolder.getFileAsync(filename).then(function (sampleFile) {
sampleFile.renameAsync(newfilename).done(
function complete(result) {
},
function error(error) {
console.log("error" + error);
}
);
});
}
问题是:重命名函数是异步的,似乎重命名有时起作用,有时却不起作用:在大多数情况下,仅列表的第一个元素被重命名。 我如何告诉循环等待,直到列表中第一个项目的重命名过程完成,然后再处理第二个,第三个...项目?
干杯
嗯,我做了一个快速查找和你的运气了。 这似乎是StorageFolder类仅有ASYN功能,你在找什么。 但是,这不是结束。
我要做的最简单的解决方案是使用递归函数。 并使用其他索引调用该函数。
function renameFile(filename, newfilename, list, index) {
Windows.Storage.ApplicationData.current.localFolder.getFileAsync(filename).then(function (sampleFile) {
sampleFile.renameAsync(newfilename).done(
function complete(result) {
renameList(list, index);
},
function error(error) {
console.log("error" + error);
}
);
});
function renameList(list, index) {
if(index >= list.length) return;
renameFile(index, index+1, list, index+1);
}
renameList(list, 0);
它不是很干净,但是应该可以工作,因为您是从回调中调用的,因此这将强制代码同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.