简体   繁体   中英

Windows 8 Javascript asynchronous programming

I want to iterate through a list and rename a few files in Windows 8 / Javascript. Therefore, I wrote a function called "renameFile" and I call this function within a loop, like this:

    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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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