nodejs循环异步回调函数

时间:2016-04-12 10:15:05

标签: node.js mongodb callback

我正在运行带有mongodb作为数据库的节点的cron作业。我试图关闭数据库连接并在curr_1每个循环完全执行后退出进程。

然而,在执行function_2时调用exit()。我知道这是由于回调而且本质上是异步的。

如何确保只在curr_1.each完成后调用exit? 没有承诺的任何解决方案?

function function_1(obj){
    var curr_1 = coll_1.find({})
    curr_1.each(function(err, doc) {
        function_2(doc)
    }); 
    exit(obj)
}
function function_2(obj) {
    coll_2.findOne({}, function(err, document) {
        dosomeprocess(obj)
    })
}
function exit(obj) {
    // Close connection
    console.log('closing connection')
    obj.db.close();
    process.exit();
}

3 个答案:

答案 0 :(得分:1)

这是Node async ....

的工作

例如:

async.each(
  curr_1, // the collection to iterate over
  function(doc, callback) { // the function, which is passed each
                            // document of the collection, and a
                            // callback to call when doc handling
                            // is complete (or an error occurs)
    function_2(doc);
  },
  function(err) { // callback called when all iteratee functions
                  // have finished, or an error occurs
    if (err) {
      // handle errors...
    }

    exit(obj); // called when all documents have been processed
  }
);

答案 1 :(得分:1)

不使用任何库:

public class Ticket extends Request implements SearchResultEntity {
    private String externalId;
    private Type type;
    private Priority priority;
    private String recipient;
    private Long submitterId;
    private Long assigneeId;
    private Long groupId;
    private List<Long> collaboratorIds;
    private List<Collaborator> collaborators;
    private Long forumTopicId;
    private Long problemId;
    private boolean hasIncidents;
    private Date dueAt;
    private List<String> tags;
    private List<CustomFieldValue> customFields;
    private SatisfactionRating satisfactionRating;
    private List<Long> sharingAgreementIds;
    private List<Long> followupIds;
    private Long ticketFormId;
    private Long brandId;
}

使用async模块

public class Request {
    protected Long id;
    protected String url;
    protected String subject;
    protected String description;
    protected Status status;
    protected Ticket.Requester requester;
    protected Long requesterId;
    protected Long organizationId;
    protected Via via;
    protected Date createdAt;
    protected Date updatedAt;
    protected Comment comment;
}

答案 2 :(得分:-1)

使用计数器简单地在循环中给出一个条件。

function function_1(obj){
var curr_1 = coll_1.find({})
var curr_1Length = curr_1.length;
var counter  = 0;
curr_1.each(function(err, doc) {
++counter;
//Check condition everytime for the last occurance of loop
if(counter == curr_1Length - 1){
exit(obj)
}
    function_2(doc)
}); 
}

希望有所帮助:)