Execute after FOR loop with FS action

206 Views Asked by At

I have a for loop that calls an action fs.copy after. After that for loop is complete I need to execute a command. I think I need to do a callback once the for is complete. The issue that I think I'm running into is the fs.copy is run async so the for loop actually completes before the fs.copy action does. Suggestions?

var sessionNumeber = 7;
photoOrder = (An array of photo names);
for(var i = photoOrder.length - 1; i >= 0; i--) {
    console.log('Moving Photo');
    fs.copy(cfg.watchedFolder+photoOrder[i]+'.jpg', cfg.outputFolder+sessionNumber+"/"+i+'.jpg', function (err) {
        if (err) {
            // i.e. file already exists or can't write to directory 
            throw err;
        }
    });
});
nextCommand();
1

There are 1 best solutions below

7
On BEST ANSWER

Because for loop is not async but copy is, so you cannot use for to loop throught async function. Solution is using async library.

https://github.com/caolan/async

async.map(arr, iteratee, [callback])

For example, you can try it:

async.map(photoOrder, function (photo, callback) {
    console.log('Moving Photo');
    fs.copy(cfg.watchedFolder + photo + '.jpg', cfg.outputFolder + sessionNumber + "/" + i + '.jpg', function (err) {
        if (err) {
            // i.e. file already exists or can't write to directory 
            callback(err);
        }
    });
}, function (err, results) {

    nextCommand();
});