代码之家  ›  专栏  ›  技术社区  ›  Jason Small Marc B

使用FS操作在FOR循环后执行

  •  -1
  • Jason Small Marc B  · 技术社区  · 8 年前

    我有一个调用动作fs的for循环。复制之后。在for循环完成之后,我需要执行一个命令。我想,在for完成后,我需要进行回调。我想我遇到的问题是fs。复制是异步运行的,因此for循环实际上在fs之前完成。复制操作可以。建议?

    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 回复  |  直到 8 年前
        1
  •  1
  •   Kelvin    8 年前

    因为 for 循环不是异步的,但 copy 是,所以您不能使用 对于 以遍历异步函数。解决方案正在使用 async 图书馆

    https://github.com/caolan/async

    异步。map(arr,iterate,[callback])

    例如,您可以尝试:

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