2017-06-15 63 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],必须确实异步 ...