Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - async.each not iterating when using promises

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.

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.

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();
        })
    })
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are only using .then() callbacks so you handle success.

But you should also add some .catch() callbacks to handle errors.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...