是否有Javascript指令可避免异步回调地狱? [英] Is there a Javascript instruction to avoid async callback hell?

查看:53
本文介绍了是否有Javascript指令可避免异步回调地狱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有Javascript指令可避免异步回调地狱?
类似于 if then else,我想象一个 do then。
例如,假设asyncFunc1(cb,errCb)是一个异步函数,成功时调用cb(),失败时调用errCb()。对于asyncFunc2,asyncFunc3等也是如此。通过正确的异步指令,我可以想象执行以下操作:

Is there a Javascript instruction to avoid the async callback hell? Similar to "if then else" I imagine a "do then". Example, suppose asyncFunc1(cb, errCb) is an async function that calls cb() on success and errCb() on failure. The same for asyncFunc2, asyncFunc3, etc. With a proper async instruction I imagine to do something like:

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

执行 do(asyncFunc1)时将调用asyncFunc1,如果执行错误,则执行括号内的代码;如果成功,则调用 asyncFunc2被执行。然后再次在出错时执行括号内的代码,在执行成功时执行 asyncFunc3。所有这些都在 var a = Math.abs(-1);同时执行。

asyncFunc1 is called when "do (asyncFunc1)" is executed, on error the code inside the brackets is executed, on success "asyncFunc2" is executed. Then again, on error the code inside the bracket is executed, on success "asyncFunc3" is executed. All this is executed at the same time of "var a=Math.abs(-1);" and of all its successive code.

承诺已经接近了,但是这样会更干净:不需要定义新函数也不需要金字塔形状。

Promises already are near, but, this would be cleaner: no need to define new functions and no pyramid shape.

注1:上面的示例与以下示例相同:

Note1: the above example is the same as:

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,...,则可以这样做:

Note2: if asyncFunc1 has arguments arg1, arg2, ... one would do:

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


推荐答案

已经可以使用js了:

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

请注意,asyncFunc [2,3]必须确实是 async

Note that asyncFunc[2,3] must be really async...

这篇关于是否有Javascript指令可避免异步回调地狱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆