Advertisement
Guest User

Untitled

a guest
Jan 5th, 2019
715
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fruits = {}
  2.  
  3. main = ->
  4.   array = [
  5.     {
  6.       fruit: 'apple'
  7.       param: 1
  8.     }
  9.     {
  10.       fruit: 'banana'
  11.       param: 2
  12.     }
  13.     {
  14.       fruit: 'cherry'
  15.       param: 3
  16.     }
  17.   ]
  18.  
  19.   array_r = array.reverse()
  20.   callback_chain = null
  21.   #把 array 的事件反過來讀取,以建立 callback chain
  22.   #產生 callback function
  23.  
  24.   createFunction = (funcToInvoke, p, callback) ->
  25.     ->
  26.       funcToInvoke.call this, p, callback
  27.       return
  28.  
  29.   #產生 callback chain
  30.  
  31.   callbackChainFactory = (fruit, param, callback) ->
  32.     createFunction fruit, param, callback
  33.  
  34.   while array_r.length
  35.     current_fruit = array_r.shift()
  36.     fruit = current_fruit.fruit
  37.     #fruit
  38.     fruitFunction = fruits[fruit]
  39.     #字串轉實際 function        
  40.     param = current_fruit.param
  41.     #parameter
  42.     callback_chain = callbackChainFactory(fruitFunction, param, callback_chain)
  43.     #建立 callback function
  44.   #執行 callback chain
  45.   callback_chain()
  46.   return
  47.  
  48. fruits.apple = (p, callback) ->
  49.   console.log 'apple, p = ' + p
  50.   setTimeout (->
  51.     if typeof callback == 'function'
  52.       callback()
  53.     return
  54.   ), 1000
  55.   return
  56.  
  57. fruits.banana = (p, callback) ->
  58.   console.log 'banana, p = ' + p
  59.   setTimeout (->
  60.     if typeof callback == 'function'
  61.       callback()
  62.     return
  63.   ), 2000
  64.   return
  65.  
  66. fruits.cherry = (p, callback) ->
  67.   console.log 'cherry, p = ' + p
  68.   setTimeout (->
  69.     if typeof callback == 'function'
  70.       callback()
  71.     return
  72.   ), 3000
  73.   return
  74.  
  75. main()
  76.  
  77. # ---
  78. # generated by js2coffee 2.2.0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement