Yeoman - 将日志记录延迟到任务完成之后

Yeoman - Delaying logging until after task completion

我对正在构建的 Yeoman Generator 的一部分感到沮丧。因为这是我的第一次,我毫不怀疑我遗漏了一些明显的东西,但就是这样。

简而言之,我正在尝试记录一条消息 Do ​​Things™,然后仅在完成这些事情后才记录另一条消息

方法如下:

repos: function () {
    var self = this;

    this.log(highlightColour('Pulling down the repositories'));

    // Skeleton
    this.remote('user', 'skeleton', 'master', function(err, remote) {
      if (!err) {
        remote.bulkDirectory('.', self.destinationRoot());
      } else {
        self.log('\n');
        self.log(alertColour('Failed to pull down Skeleton'));
        repoErr = true;
      }
    });

    //
    // Three more near identical remote() tasks
    //

    if (!repoErr) {
      self.log(successColour('Success!'));
      self.log('\n');
    } else {
      self.log(alertColour('One or more repositories failed to download!'));
    }
  },

每个单独的 remote() 任务都工作正常,但我收到了第一个和最后一个 self.log() 消息 文件复制发生之前。这看起来微不足道,但我只是希望在一切都完成后出现成功消息。

例如,在终端中我看到:

Pulling down the repositories

Success!

file copying results

应该是:

Pulling down the repositories

file copying results

Success!

我认为这可能与在每个 remote() 任务结束时将 this.async() 与 done() 一起使用有关,我试过了,但每当我这样做时,none 的代码完全触发。

我什至尝试将所有内容(包括消息)分解为单独的方法,但仍然没有成功。

这么简单的目标,我却一窍不通!非常感谢您的帮助!

编辑:如果您想知道,我知道消息会先出现,因为有关文件冲突的任何警报都会在消息之后出现:)

这不是与 Yeoman 相关的问题。您有异步代码,但您在处理它时就好像它是同步的一样。

在您在此处发布的示例中,只需将日志记录作为 this.remote 回调的一部分:

repos: function () {
  var self = this;

  this.log(highlightColour('Pulling down the repositories'));

  // Skeleton
  this.remote('user', 'skeleton', 'master', function(err, remote) {
    if (!err) {
      remote.bulkDirectory('.', self.destinationRoot());
      self.log(successColour('Success!'));
      self.log('\n');
    } else {
      self.log('\n');
      self.log(alertColour('Failed to pull down Skeleton'));
      self.log(alertColour('One or more repositories failed to download!'));
    }
  });
},

也许您的实际用例更复杂;在这种情况下,您可以使用 async 之类的模块(或任何其他替代方法)来处理更复杂的异步流。无论哪种方式,Yeoman 都不提供帮助程序来处理异步代码,因为这是 Node.js.

的基础