ループをsetTimeoutでまわす、Afrous版

とみたが最近かかりっきりのAfrousは、元を正せばJavaScriptの非同期実行=>同期実行の変換エンジンだったりします。つまりこれとかの後継。

ということで、setTimeoutって、まあコールバックで処理が非同期で返ってくるわけなんで、Afrousでまわせます。

<html><head>
<script type="text/javascript" src="http://sandbox.afrous.com/js/afrous/afrous-core.js"></script>
<script type="text/javascript" src="http://sandbox.afrous.com/js/afrous/afrous-package.js"></script>
<script type="text/javascript">

function timeout_loop(array, func, callback) {
  var packName = 'Loop'+new Date().getTime();
  var pack = new afrous.UnitActionPackage(packName);

  pack.register(new afrous.UnitAction({
    type : 'LoopFunc',
    inputs : [ { name : 'element', type : 'Object' },
               { name : 'index', type : 'Integer' } ],
    execute : function(request, callback) {
      func(request.params['element'], request.params['index'], callback.onSuccess);
    }
  }));
  afrous.packages.register(pack);

  var procdef = new afrous.ProcessDef({
    params : [ 
      { name : "array", type : "object[]" } 
    ],
    actions : [
     { type : "Array.Iterate", 
       name : "iterate",
       inputs : { array : "${array}" },
       innerProcess : { 
         actions :[ 
          { type : packName+'.LoopFunc',
            name : "loopfn",
            inputs : { element : "${element}", index : "${index}" }
          }],
         output : "${loopfn}"
       }
     }
    ],
    output : "${iterate}"
  });

  var proc = new afrous.ProcessInstance(procdef);
  proc.setParam('array', array);
  proc.start(callback || function(){});
}


// main
var aa = [];
var num = 3;
for (var i=0; i<num; i++) aa.push(i);

timeout_loop(aa, function(a1, i, c) {
  timeout_loop(aa, function(a2, i, c) {
    alert(a1+','+a2); setTimeout(c, 1000);
  }, c);
})
</script>
</head></html>

テスト

実はAfrousの内部で、コールバックを次にまわすところでsetTimeoutもしてるんで、functionの中でsetTimeoutは必要なかったりします。

ああ、でも、パッケージとかわざわざ作ってて、めんどくさい!何かさくっと使える感じじゃない!Web IDE化したことの弊害かもしれんけど、もうちょっとスクリプト側からもフレンドリーにしたいな。