0

I'm trying to build a small electron app. It gets a file/files from the user, then copies them to a specific folder, and adds all the info about that file to a database.

const fs = require('fs-extra')
//sample 2 file entry
files = {"0":{"name":"File1.png","path":"A:\\User Folders\\Desktop\\File1.png"},"1":{"name":"File2.jpg","path":"A:\\User Folders\\Desktop\\File2.jpg"},"length":2}
window.$ = window.jQuery = require('jquery');

jQuery.each(files, function(file) {
    //this is just one of many variables I need
    currentfile = files[file].path
    fs.copy(currentfile, "./files/"+"."+files[file].name, function (err) {
        if (err) {
            console.log(err)
        } else {
            console.log(currentfile);
            //I expect this to log file1 then file2 so I can submit it to my database,
            //but it always logs file2

        }
    })
});

It works fine for one file at a time, but when I try to handle more than one it doesn't work as I expect it (copy a file, update the DOM, copy next file, updates DOM, etc).

Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90

1 Answers1

2

I think you accidentally declared a variable with global scope when you probably want local.

Change this:

currentfile = files[file].path

to this:

var currentfile = files[file].path

This will form a closure where the anonymous function that handles the error will be able to access the currentfile variable in the anonymous function that handles the jquery each.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • 2
    *"This will form a closure..."* This *will not* form a closure. It *will* declare the variable in the current lexical environment instead of the global environment. The function statement is what creates the lexical environment, or "closure". Also, w3schools may not be the best reference. –  Nov 29 '16 at 00:22
  • Thanks, I didn't know there was so much of a difference (still a noob here). What I don't get is even though is why even though that was creating a global variable, it didn't work. I would assume that for each file it would change the variable to that current file, use it to do stuff, then on the next file, change it again, and so on. I'm reading up on using vs vs not, to try and understand it, but if you could explain how things were going wrong that'd be very helpful. – Jack Taylor Nov 29 '16 at 01:59
  • It's asynchronous. By the time your error handler is called, the `each` loop may have moved on to other records, updating the `currentFile` variable in a manner that the error handler isn't expecting. – John Wu Nov 29 '16 at 02:02