async.each not iterating when using promises

后端 未结 2 1688
执笔经年
执笔经年 2020-12-12 05:27

I am trying to run an asynchronous loop async.each over an array of objects. On each object in the array, I am trying to run two functions sequentially (using

2条回答
  •  无人及你
    2020-12-12 06:25

    It turns out that that I made an error in the getKeywords function. I was reading from a file, then iterating through each line by using a for loop and pushing the result to an array. This array was then returned by the function.

    async.each was working perfectly but was only ever receiving an array of length 1 to iterate over.

    I fixed this problem by changing the for loop to an async.each loop

    function getKeywords(keywordsFilename){
        //get keywords from the file
        return new Promise( function (resolve, reject) {
            var keywords = [];
            fs.readFile(keywordsFilename, function read(err, data) {
                if (err) {
                    reject(err);
                }
                content = data.toString();
                var lines = content.split("\n");
                async.each(lines, function(line, callback) {
                    if (line[0] === "#" || line == "") {
                        callback();
                    }
                    else {
                        keywords.push(extractKeyword(line));
                        callback();
                    }
                }, function (err) {
                    resolve(keywords);
                });
            });
        });
    }
    

    Writing the problem out helped, let me know if I should delete the question.

    Thanks for your help Mukesh Sharma and rsp.

提交回复
热议问题