async.each在使用promises时不迭代 [英] async.each not iterating when using promises

查看:239
本文介绍了async.each在使用promises时不迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个对象数组上运行异步循环 async.each
在数组中的每个对象上,我试图按顺序运行两个函数(使用 promises )。问题是 async.each 仅针对第一个关键字运行。

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 promises). The problem is that async.each only runs for the first keyword.

在以下代码中, getKeywords 从文件中加载一些关键字,然后返回一个关键字对象数组。每个关键字对象都放入进行搜索的 searchKeyword 中。然后使用 InsertSearchResults 将搜索结果放入数据库。

In the following code, getKeywords loads some keywords from a file, then returns an array of keyword objects. Each keyword object is put into searchKeyword that makes a search. The search result is then put into a database using InsertSearchResults.

在我看来,每个关键字都应该在parallel和search和insert函数是链接的。

In my mind, each keyword should be processed in parallel and the search and insert functions are linked.

getKeywords(keys).then(function(keywords) {
    async.each(keywords, function(keywordObject, callback) {
        searchKeyword(keywordObject).then(function(searchResults) {
            return insertSearchResults(searchResults, db, collections);
        }).then(function(result) {
            console.log("here");
            callback();
        })
    })
})


推荐答案

事实证明我在getKeywords函数中犯了一个错误。
我正在读取文件,然后使用for循环遍历每一行并将结果推送到数组。然后该函数返回此数组。

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工作正常,但只接收长度为1的数组进行迭代。

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

我通过将for循环更改为async.each循环来修复此问题

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.

感谢您的帮助Mukesh Sharma和rsp。

Thanks for your help Mukesh Sharma and rsp.

这篇关于async.each在使用promises时不迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆