2017-06-15 68 views
-1

有沒有Javascript指令來避免異步回調地獄? 與「if then else」類似,我想象一下「do then」。 例如,假設asyncFunc1(cb,errCb)是一個異步函數,它在成功時調用cb(),在失敗時調用errCb()。同爲asyncFunc2,asyncFunc3,等有了合適的異步指令我想象做這樣的事情:當「做(asyncFunc1)」執行有沒有Javascript指令來避免異步回調地獄?

do (asyncFunc1) { 

    // error code for failure of asyncFunc1 goes here 

} then (asyncFunc2) { 

    // error code for failure of asyncFunc2 goes here 

} then (asyncFunc3) { 

    // error code for failure of asyncFunc3 goes here 

} // etc... 

var a=Math.abs(-1); // first synchronous code. This, and all the 
// following code, is executed at the same time of 
// the "do (asyncFunc1) { } then ... {}" block 

asyncFunc1被調用,在錯誤執行括號中的代碼,成功執行「asyncFunc2」。然後再次,錯誤地執行括號內的代碼,成功執行「asyncFunc3」。所有這些都是在「var a = Math.abs(-1);」的同時執行的。及其所有後續代碼。

承諾已經接近,但是,這將是更清潔:不需要定義新的功能和金字塔形狀。

注1:上述例子是一樣的:

asyncFunc1(
    function() { 

     asyncFunc2(
      function() { 

       asyncFunc3(

        // etc... 

         function() { 

          var a=Math.abs(-1); // first call of a synchronous function here 

         }, 
         function() { 
          // error code for failure of asyncFunc3 goes here 
         } 
       ) 

      }, 
      function() { 

       // error code for failure of asyncFunc2 goes here 
      } 
     ) 

    }, 
    function() { 

     // error code for failure of asyncFunc1 goes here 
    } 
) 

注2:如果asyncFunc1有爭論ARG1,ARG2,...一會做:

do(asyncFunc1, arg1, arg2, ...) { } 
+3

mm ...這正是Promises所做的... https://developer.mozilla.org/zh/docs/Web/JavaScript/Reference/Global_Objects/Promise – nicowernli

+1

歡迎來到SO。請訪問[幫助],看看有什麼和如何問。您的問題與SO主題無關,但可能在codereview或JS論壇上有效 – mplungjan

+3

JavaScript具有'async'功能:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function –

回答

1

。這是你能做的事已經做JS:

(async function(){ 
try{ 
    await asyncFunc(); 
    await asyncFunc2(); 
    await asyncFunc3(); 
    alert("allfinished"); 
}catch(error){} 
})(); 

注意asyncFunc [2,3],必須確實異步 ...