代码之家  ›  专栏  ›  技术社区  ›  EyWN

NodeJ使用异步for循环下载

  •  0
  • EyWN  · 技术社区  · 7 年前

    但文件的下载顺序是“2,3,4,1,5”,而不是“1,2,3,4,5”。

    我知道怎么做。每个异步和瀑布异步,但我不知道如何做这个循环。

    Config.TotalFiles = 5;
    
    for(i = 1; i <= Config.TotalFiles; i++) {
       $this.CreateJSONFile(i, function() {
         cls();
       });
    }
    

    当下载完成后,我想调用我的回调,我已经尝试了这个 if(id == Config.TotalFiles)

    如何使用此循环执行“异步”过程?

    谢谢

    3 回复  |  直到 7 年前
        1
  •  1
  •   Kamesh    7 年前

    您可以使用异步。同时:

    Config.TotalFiles = 5;
    var count = 1;
    
    //pass your maincallback that you want to call after downloading of all files is complete.
    
    var callMe = function(mainCallback){
        async.whilst(
            function() { return count <= Config.TotalFiles; },
            function(callback){
                $this.CreateJSONFile(count, function() {
                    cls();
                    count++;
                    callback();
                });
            }, function(){
               //This function is the final callback
               mainCallback();
            })
    }
    
        2
  •  0
  •   Artem    7 年前

    是的,您需要实现异步for循环。主要思想是在当前步骤完成后调用回调(如continue)。您可以使用上面提到的一些有用的库(async.js)。但你也必须明白,这不会并行进行(因此完成下载的时间会增加)。

    以下是一些很好的例子可以帮助您: https://github.com/caolan/async/blob/v1.5.2/README.md#whilst

        3
  •  0
  •   EyWN    7 年前

    请查看我的屏幕以了解我的情况。

    http://imgur.com/a/lxQyy

    https://pastebin.com/jtANeSxq

                    cls();
                    for(i = 1; i <= Config.TotalFolders; i++) {
                        $this.CreateJSONFile(i, function() {
                            setTimeout(function() {
                                cls();
                            }, 200);
                        });
                    }
    
        CreateJSONFile(id, callback) {
        console.log(chalk.hex("#607D8B")(`Creating JSON Files... [${id}/${Config.TotalFolders}]`));
        var requestOptions = {
            encoding: "binary",
            method: "GET",
            uri: `${Config.Url.Source}${Config.Url.Audio}` + `${id}/skeud.json`
        };
        request(requestOptions, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                if(!fs.existsSync(Config.DownloadsPath + `${id}/skeud.json`)) {
                    fs.writeFile(Config.DownloadsPath + `${id}/skeud.json`, body, function(err) {
                        if(err) {
                            return console.log(err);
                        }
                        console.log(chalk.hex("#FFEB3B")(`JSON File ${chalk.inverse(id)} ${chalk.hex("#FFEB3B")("created")}`));
                    });
                } else {
                    console.log(chalk.hex("#FFEB3B")(`JSON File ${chalk.inverse(id)} ${chalk.hex("#FFEB3B")("skipped")}`));
                }
            }
        });
        /*if(created == Config.TotalFolders) {
            callback();
        }*/
    }
    

    谢谢