简体   繁体   English

Windows 8 Javascript异步编程

[英]Windows 8 Javascript asynchronous programming

I want to iterate through a list and rename a few files in Windows 8 / Javascript. 我想遍历列表并重命名Windows 8 / Javascript中的一些文件。 Therefore, I wrote a function called "renameFile" and I call this function within a loop, like this: 因此,我编写了一个名为“ 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);
            }
            );
    });
}

The problem is: The rename function is asynchronous and it seems that sometimes, the renaming works and sometimes not: In most cases, only the first element of the list is renamed. 问题是:重命名函数是异步的,似乎重命名有时起作用,有时却不起作用:在大多数情况下,仅列表的第一个元素被重命名。 How can I tell the loop to wait, till the rename-process of the first item in the list is finished and then go an with the second, third, ... item? 我如何告诉循环等待,直到列表中第一个项目的重命名过程完成,然后再处理第二个,第三个...项目?

Cheers 干杯

Well I did a fast lookup and you're out of luck. 嗯,我做了一个快速查找和你的运气了。 It seems like the StorageFolder class only has Asyn functions for what you're looking for. 这似乎是StorageFolder类仅有ASYN功能,你在找什么。 But it's not the end. 但是,这不是结束。

The easiest solution I have to do use a recursive function. 我要做的最简单的解决方案是使用递归函数。 And call the function with a different index. 并使用其他索引调用该函数。

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);

It's not very clean but it should work, this will force the code to be synchrone since you're calling from within a callback. 它不是很干净,但是应该可以工作,因为您是从回调中调用的,因此这将强制代码同步。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM