简体   繁体   English

使用promises时async.each不迭代

[英]async.each not iterating when using promises

I am trying to run an asynchronous loop async.each over an array of objects. 我试图在对象数组上运行异步循环async.each On each object in the array, I am trying to run two functions sequentially (using promises ). 我试图在数组中的每个对象上依次运行两个函数(使用promises )。 The problem is that async.each only runs for the first keyword. 问题在于async.each仅针对第一个关键字运行。

In the following code, getKeywords loads some keywords from a file, then returns an array of keyword objects. 在以下代码中, getKeywords从文件中加载一些关键字,然后返回关键字对象的数组。 Each keyword object is put into searchKeyword that makes a search. 每个关键字对象都放入进行搜索的searchKeyword中。 The search result is then put into a database using InsertSearchResults . 然后使用InsertSearchResults将搜索结果放入数据库中。

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

You are only using .then() callbacks so you handle success. 您仅使用.then()回调,因此您可以处理成功。

But you should also add some .catch() callbacks to handle errors. 但是,您还应该添加一些.catch()回调来处理错误。

Most likely you get errors that are not handled and nothing happens. 您很可能会遇到无法处理的错误,并且什么也没有发生。

For example: 例如:

            // ...
        }).then( function(result) {
            console.log("here");
            callback();
        }).catch(function (error) {
            console.log('Error:', error);
            callback(error);
        });

It turns out that that I made an error in the getKeywords function. 原来,我在getKeywords函数中犯了一个错误。 I was reading from a file, then iterating through each line by using a for loop and pushing the result to an array. 我正在从文件中读取内容,然后使用for循环遍历每一行并将结果推入数组。 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. async.each工作得很好,但是只收到长度为1的数组进行迭代。

I fixed this problem by changing the for loop to an async.each loop 我通过将for循环更改为async.each循环来解决此问题

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. 感谢您的帮助Mukesh Sharma和rsp。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM