2010-12-21 19 views
5

請問您向我解釋如何在JavaScript中編寫真正基本的流程控制?謝謝。JavaScript中的基本流程控制

flow([ 

    function(callback) { /* do something */ callback(); /* run next function */ }, 
    function(callback) { /* do something */ callback(); /* run next function */ }, 
    function(callback) { /* do something */ callback(); /* run next function */ }, 
    function(callback) { /* do something */ callback(); } 

], function() { 

    alert("Done."); 

}); 
+3

...你能否詳細解釋一下你想做什麼? – deceze 2010-12-21 01:31:19

+0

我想寫這個流量控制,但我不知道如何。我瀏覽了很多代碼,但我沒有得到它。 – 2010-12-21 01:34:45

+0

函數可能是異步的嗎? – slebetman 2010-12-21 01:42:07

回答

0
(function(){ 
    function a(cb) { alert('hi'); cb(); } 
    function b(cb) { alert('there'); cb(); } 
    function c(cb) { alert('replace alert with console.log for ease'); cb(); } 
    var done = function() { alert('done'); } 
    a(b(c(done))); 
})() 
0
// callback is a global function, I assume 

function flow(funcArr, funcEnd) {  
    for (var i = 0; i < funcArr.length; i++) { 
     funcArr[i](callback); 
    }  
    funcEnd(); 
} 

這將運行所有這些功能。

+0

但如果它們是異步的,則不按指定順序。 – slebetman 2010-12-21 01:41:36

+0

是的。我願意按照指定的順序運行這些函數。 – 2010-12-21 01:43:32

+0

@slebetman我的代碼工作方式是所有函數都是同步的。 – 2010-12-21 01:43:35

7

會這樣的工作?

function flow(fns, last) { 
    var f = last; 
    for (var i = fns.length - 1; i >= 0; i--) 
     f = makefunc(fns[i], f); 
    f(); 
} 

function makefunc(f, g) { 
    return function() { f(g) } 
} 
+0

這個答案簡短,優雅,正確。 – 2010-12-21 02:20:54

+0

var f =最後完成了什麼? – qwertymk 2010-12-21 04:16:49

+1

@qwertymk:'f'用'last'初始化並從那裏建立起來。首先,它是'最後的'。然後,它是'makefunc(fns [n-1],last)',後面是'makefunc(fns [n-2],makefunc(fns [n-1],last))'等等。 [cons list](http://en.wikipedia.org/wiki/Cons),其中'makefunc'是「cons」,'last'是「nil」。 – 2010-12-21 06:52:26

1

我在最近的一個項目中做了很多。我寫了一些代碼來幫助管理它。這是代碼。您使用「calls」參數和「bundleCallback」參數將bundledAsync函數傳遞給一個對象。 calls參數是一個代表要調用的函數的objets數組。在fn參數中,存儲對實際參數的引用。在「args」參數中,你存儲你的參數。你傳入的每個函數的最後一個參數必須是一個回調函數,它必須被調用。

我很遺憾記錄我的代碼並使其對別人有用,但這對我來說確實非常有用。我懷疑別人寫了類似的東西,或許有適當的文件記錄。如果你找不到它,並且需要幫助解決這個問題,請告訴我。

/** 
    This is a way to submit multiple async calls, and be notified when they've all finished 

    <pre> 

    NameSpace.bundledAsync({ 
    calls:[ 
     { 
     fn: service.getGroups, 
     args: [ 
      function(listsArg){ 
      listsSummary = listsArg; 
      } 
     ], 
     calls: function(){return UNAB.Util.makeArray(listsSummary, function(list){ 
      return { 
      fn: service.getGroup, 
      args: [list.id, function(resp){listsDetail.push(resp)}] 
      } 
     })} 
     } 
    ], 
    bundleCallback: function(){ 
     callback(listsDetail) 
    } 
    }); 

    </pre> 

    @class bundledAsync 
    @static 

*/ 

NameSpace.bundledAsync = function(options){ 

    var callbacksLeft = 0; 
    var calls = $.grep(options.calls, function(call){return call}); 


    if(options.hasOwnProperty("bundleCallback") && typeof options.bundleCallback != "function"){ 
     throw new Error("bundleCallback, passed to bundledAsync, must be a function."); 
    } 

    if(options.chain){ // if this is true, sibling calls will run in succession, not in parallel 
     calls.reverse(); 
     var newCalls = [calls.pop()]; 
     var lastCall = newCalls[0]; 
     while(calls.length > 0){ 
     if(lastCall.calls){ 
      throw new Error("You can't nest calls if you're in chain mode"); 
     } 
     lastCall.calls = [calls.pop()]; 
     lastCall = lastCall.calls[0]; 
     } 
     calls = newCalls; 
    } 

    var decrimentCallbacksLeft = function(){ 
     if(options.name){ 
     // log.debug("Starting decrimentCallbacksLeft for: " + options.name + ". Decrimenting callbacksLeft to: " + (callbacksLeft - 1)); 
     } 
     if(--callbacksLeft == 0 && options.bundleCallback){ 
     // log.debug("No callbacks left. Calling bundleCallback for name: " + options.name); 
     options.bundleCallback(); 
     } 
    } 

    var doCalls = function(callsToDo){ 

     if(typeof callsToDo == "function"){ 
     callsToDo = callsToDo(); 
     }else{ 
     callsToDo = $.extend(true, [], callsToDo);// in case we want to reuse the calls 
     } 

     // right away, return if the calls are empty 
     // check to make sure callbacksLeft == 0, because 
     // we may be dealing with nested calls 
     if(callsToDo.length ==0 && callbacksLeft == 0){ 
     // log.debug("callsToDo is empty, so call the callback right away."); 
     options.bundleCallback(); 
     return null; 
     } 

     callbacksLeft += callsToDo.length; 
     $.each(callsToDo, function(index, call){ 
     var numFns = 0; 
     // // Look through the args searching for functions. 
     // // When one is found, wrap it with our own function. 
     // // This assumes that each function has exactly one 
     // // callback, and that each callback is called exactly once 
     // args can be a function which will return the args, 
     // that way, you don't have to determine the args for the function until the moment it's called 
     call.args = call.jitArgs? call.args():call.args; 
     $.each(call.args, function(index, arg){ 
      if(typeof arg === "function"){ 
      numFns++; 
      // Here's where we wrap the original function's callback 
      call.args[index] = function(){ 
       // when we get to this point, we know that the original function has totally completed, 
       // and we can call any functions chained to this one, or finish the whole process 
       arg.apply(null, arguments); // call the original callback 
       if(call.calls){ 
       // maybe we don't want to create the child calls until after 
       // the parent has returned. In that case, pass a function instead of an array 
       if(typeof call.calls === "function"){ 
        call.calls = call.calls(); 
       } 
       // if this call has any call of its own, send those out now 
       doCalls(call.calls); 
       } 
       decrimentCallbacksLeft(); 
      } 
      } 
     }); 
     if(numFns!=1){ 
      throw new Error("Each function passed to bundledAsync must have one and only one arg which is a function"); 
     } 
     // if(call.fn.length != call.args.length){ 
     // log.warn("The current function is being called with a different number of arguments that that with which it was declared. Should be: "+call.fn.length+", was: "+call.args.length+" \n" + call.fn.toString()); 
     // } 
     call.fn.apply(null, call.args); 
     }); 
    } 

    doCalls(calls); 
    } 
1

我推薦閱讀約continuation-passing style。看起來你的目標是,給定一組採用延續參數的函數,將它們鏈接在一起,以便繼續進行到數組中的下一個函數。

這裏有這樣的功能的實現:

function flow(funcArr, funcDone) { 
    function proceed(i) { 
     if (i < funcArr.length) { 
      return function() { 
       funcArr[i](proceed(i+1)); 
      } 
     } else { 
      return funcDone; 
     } 
    } 

    proceed(0)(); 
} 

編輯:Anon.'s answer較短和簡單。

下面是它如何工作的:proceed(i)返回它調用我功能(或者,funcDone,如果沒有在陣列中左)回調。因爲proceed(i)返回一個回調而不是這樣做,我們可以使用proceed(i+1)作爲contiunation函數。

使用範例:

flow([ 

    function(cb) { print("Thing one"); cb(); }, 
    function(cb) { print("Thing two"); cb(); }, 
    function(cb) { print("Thing three"); cb(); }, 
    function(cb) { print("Thing four"); cb(); }, 

], function() { 

    print("Done."); 

}); 

現在嘗試刪除cb();調用之一。它會打破這個鏈條,這可能正是你想要的。另一件很酷的事情是,你可以拿cb,把它放在一個全局變量中,稍後再調用它來恢復流。

請記住,這種方法存在一個缺點:很多(如果不是全部的話)JavaScript解釋器不優化尾遞歸。如果funcArr太長,則可能會發生堆棧溢出。這是任何使用JavaScript中的continuation-passing樣式的交叉。