0

I have a task, and if it's been done, already, I need to skip it, and if it hasn't, I need to perform it. The task is asynchonous. After this, I need to do the same check for another task, and possibly perform it...

if(!taskStatus.complete[x])
  asyncTasks[x](function(result){
    if(!taskStatus.complete[y])
      asyncTasks[y](function(result){
        stow(result);
      });
  });
if(!taskStatus.complete[y])
  asyncTasks[y](function(result){
    stow(result);
  });

In other words, the second task needs to be performed regardless of whether or not the first gets done, but if the first is to be done, the second cannot happen until after it finishes.

My code has repeated itself quite a bit here, which is generally a very bad thing. Is it unavoidable for Node's hipness? Is Node too hip to be DRY?

4

1 回答 1

1

你应该进入 promises (这里是一个很好的实现 promises 的库)。它们允许您优雅地表示代码的异步函数之间的依赖关系。

如果您将函数转换为使用 Promise,以下是您的特定用例的示例:

getSomeX()
.then(getSomeY)
.then(function(result) {
    stow(result);
})

这很好地表明您只想stow()在 Y 完成后调用,并且 Y 首先需要 X。

这是一个关于如何将函数转换为使用 Promise的示例(以及相应的教程,使用 Deferreds小节):

var Q = require('q');
var getSomeX = function() {
    var deferred = Q.deferred();
    asyncTasks[x](function (result) {
        deferred.resolve(result);
    });
    return deferred.promise;
}

编辑:您还可以使用 Q 的功能自动转换一个异步函数,该函数尊重 Node 通常的回调样式(错误,结果)与denodeify函数:

var getSomeX = Q.denodeify(asyncTasks[x]);
于 2013-11-16T16:43:28.733 回答