毕竟回归" on"事件在JS承诺中调用

时间:2017-02-06 05:10:42

标签: javascript node.js promise nodegit

在Node.js中,使用NodeGit。我在POST Express.js路由中使用类似于this的函数。此路由应该在 endCommit startCommit 之间进行提交:

router.post('/getLog', function(req, res, next) {
    var logData = [];

    Git.Repository.open(path.join(repositories.mine.path))
        .then(function(repo) {
            return {
                    endCommit: [ First commit object ], //Just a random commit object that has a "sha" inside
                    startCommit: [ Second commit object ]  //Just a random commit object that has a "sha" inside
                };
        })
        .then(function(range) {
            // History returns an event.

            var history = range.endCommit.history(Git.Revwalk.SORT.Time);

            // History emits "commit" event for each commit in the branch's history
            history.on("commit", function(commit) {
                logData.push({
                    commit: commit.sha(),
                    message: commit.message()
                });

                if (commit.sha() == range.startCommit.sha()) {
                    console.log("---LOG CREATED---");
                    history.end();
                }
            })

            history.start();
        })
        .done(function() {
            console.log("---RETURNING---");

            return res.json({ logData: logData });
        });
});

但是,由于history.on("commit", ...)不是Promise,因此首先调用.done()函数。在日志中我看到:

---RETURNING---
---LOG CREATED---

如何在创建日志后才能返回?

我过去遇到过这样的问题,但在这个特殊情况下,我不知道如何宣传历史对象,因为它基于事件。 / p>

1 个答案:

答案 0 :(得分:1)

您可以将事件处理包装在应该在完成后解决的承诺中,并将其返回:

.then(function(range) {
  // History returns an event.

  var history = range.endCommit.history(Git.Revwalk.SORT.Time);

  var commitPromise = new Promise(function(resolve, reject) {
    // History emits "commit" event for each commit in the branch's history
    history.on("commit", function(commit) {
      logData.push({
        commit: commit.sha(),
        message: commit.message()
      });

      if (commit.sha() == range.startCommit.sha()) {
        console.log("---LOG CREATED---");
        resolve(); // resolve the promise
        history.end();
      }
    })
  });

  history.start();

  return commitPromise;
})

我假设你有Promise全球。这取决于您选择特定的承诺实现 - 例如,您可能希望使用bluebird