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

标签 javascript yeoman

我对我正在构建的 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() 和 did() 有关,并且我尝试了这一点,但每当我这样做时,都不会触发任何代码。

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

这么简单的目标,但我没有主意!我将非常感谢您的帮助!

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

最佳答案

这不是与 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 的面包和黄油。

关于javascript - Yeoman - 将日志记录延迟到任务完成后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31907044/

相关文章:

JavaScript 同步 Ajax 请求特性

javascript - Jquery 禁用选定的选项

angularjs - 客户端与服务器通信时如何克服 "Access-Control-Allow-Origin"错误

javascript - 如何内联或通过 javascript 设置 css3 动画?

javascript - react - 使用 react-table 超出最大更新深度

javascript - 如何嵌入以 JSON 返回的 HTML <tag>

javascript - 我应该为新的 Angular 应用程序使用 angular-seed 还是 yeoman?

windows - 删除 node_modules 文件夹

javascript - 在 grunt 中不存在时创建文件/文件夹的任务

javascript - 处理 ember.js 中的页面标题