难以包装javascript行为并将其保留以供日后使用

Cie*_*iel 5 javascript promise q

我正在使用javascript进行编程并使用Promises,现在正在使用Q.js.我终于明白我在理解我在做什么,但是我遇到了特定行为的困难时期.

我有一种情况,我有相似的相似代码重复几次.它基本上就是这样......

{
   // start
   var deferred = Q.defer();

   // do something {
      deferred.resolve();
   }

   return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)

好吧,这一切都很好,但每次重复这一切都很烦人,所以我试图将它包装成一些东西.这只是一个例子,它不是整个javascript文件,因为大多数其他部分都不相关.

{
   var list = [];
   queue = function(f) {
      var deferred = Q.defer();
      list.push(f(deferred));
      return deferred.promise;
   }

   {
      queue(function(deferred){
         // do some work
         // we want the deferred here so we can resolve it at the correct time
         deferred.resolve();
      });
   }
}
Run Code Online (Sandbox Code Playgroud)

问题是我不想让它在我排队的那一刻运行.我基本上想要构建列表,然后再运行它.我正在使用reduce函数运行列表Q.js

{
   return list.reduce(function(i, f) {
      return i.then(f);
   }, Q());
}
Run Code Online (Sandbox Code Playgroud)

但这与我的目标背道而驰,因为我真的不打算在他们排队的同时运行它们.有没有办法保存执行以便以后仍然通过函数传递延迟对象?

更新

我被问到了我期望代码做什么,这是一个公平的问题.我会试着解释一下.这样做的目的是分解逻辑,因为我正在使用ASP.NET MVC,所以我有_Layout页面,然后是普通视图 - 所以有逻辑在其他事情完成之前无法运行,但有时是基于每页.这种方法是为了解决这个问题而设计的.

基本上它就像这样......

Loader.js

由于缺乏更好的术语或当前实现,这是一个全局对象.我计划最终改变这一点,但一步一步.

{
   var Loader = {};
   var list = [];

   initialize = function() {
      Q().then(step1).then(step2).then(process).then(finalStep);
   };

   queue = function(f) {
      // push the given function to the list
   };

   process = function() {
      return list.reduce(function(i,f){ 
         return i.then(f);
      }, Q());
   };

   step1 = function() { // generic example
      // create a promise
      return deferred.promise;
   }; // other steps are similar to this.

   return Loader;
}
Run Code Online (Sandbox Code Playgroud)

_布局

<head>
   @RenderSection("scripts", false)
   <script type="text/javascript">
      // we have the loader object already
      Loader.initialize();
   </script>
</head>
Run Code Online (Sandbox Code Playgroud)

指数

@section Scripts {
   <script type="text/javascript">
      Loader.promise(function(deferred){
         // do something here.
         deferred.resolve();
      }));
   </script>
}
Run Code Online (Sandbox Code Playgroud)

小智 6

你可以使用一个闭包.

queue(function(deferred) {
    return function() {
        // this is the actual function that will be run,
        // but it will have access to the deferred variable
        deferred.resolve();
    };
});
Run Code Online (Sandbox Code Playgroud)