0

我的目标很简单。我有一堆按各种顺序调用的异步实用程序函数。

不是这样的:

doSomething(doNextThing(doFinalThing));

但它变得笨拙。我的目标是有这样的语法:

doSomething.then(doNextThing).then(doFinalThing)

但具有改变订单的能力:

doNextThing.then(doSomething).then(doFinalThing)

我将如何实现这些功能以使它们都具有承诺意识?

4

2 回答 2

1

每个函数都需要返回一个在其异步任务完成时完成的 Promise。查看许多现有的 Promise 库之一。一个很好的是Q

然后您将按顺序调用这些函数,如下所示:

var promiseForFinalResult = doSomething().then(doNextThing).then(doFinalThing);

假设每个函数只接受一个参数——前一个函数的结果。


使用“Q”的实现doSomething()可能看起来像这样:

function doSomething() {
   var D = Q.defer();
   kickOffSomeAsyncTask(function(err, result) {
       // this callback gets called when the async task is complete
       if(err) {  
           D.fail(err); 
           return;
       }
       D.resolve(result);
   });
   return D.promise;
}

查看“Q”的文档。的文档Q.defer位于此处,但您可能需要先阅读前面的一些内容,然后再直接了解延迟。

于 2013-09-08T03:53:36.377 回答
0

通常,您在这种情况下所做的是将变化的部分抽象为变量或函数参数:

function chainStuff(first, second, third){
   return first.then(second).then(thrid)
}

然后,您可以在运行时选择绑定到每个参数的回调(第一个、第二个、第三个)

if(condition){
    return chainStuff(doSomething, doNextThing, doFinalThing)
}else{
    return chainStuff(doNextThing, doSomething, doFinalThing)
}
于 2013-09-08T04:53:17.430 回答