当使用链式承诺时,最后在`.then`之前执行

时间:2015-02-19 12:15:03

标签: node.js promise rsvp.js

为什么我的上一个.then( writeLin .. )没有运行?

注意:triggercommand返回返回promise

的函数
 .then(function () {

    if (fs.existsSync(tempDir + '/' + repoName)) {
      return self.triggerCommand("git", ["checkout", "master"], {cwd: tempDir + '/' + repoName})()
        .then(
        self.triggerCommand("git", ["pull", "master"], {cwd: tempDir + '/' + repoName})
      )
    }
    return self.triggerCommand("git", ["clone", remote], {cwd: tempDir});
  }
)

  .then(
    writeLine("Git clone/pull complete.")//this never runs
)

.finally(function () {
    //this runs

1 个答案:

答案 0 :(得分:2)

根据Promises规范,then函数应接收函数,只要解析了promise,就会调用该函数。

您的writeLine("Git clone/pull complete.")将在配置then链时运行,因为未包含在函数中

修复很简单:

.then(function () {
    if (fs.existsSync(tempDir + '/' + repoName)) {
      return self.triggerCommand("git", ["checkout", "master"], {cwd: tempDir + '/' + repoName})()
        .then(
        self.triggerCommand("git", ["pull", "master"], {cwd: tempDir + '/' + repoName})
      )
    }
    return self.triggerCommand("git", ["clone", remote], {cwd: tempDir});
  }
)
.then(function(){
  writeLine("Git clone/pull complete.")
})
.finally(function () {
    //this runs
})