【问题标题】:Is there a Javascript instruction to avoid async callback hell? [closed]是否有避免异步回调地狱的 Javascript 指令? [关闭]
【发布时间】:2017-11-18 01:34:48
【问题描述】:

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

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);”的同时执行的及其所有后续代码。

Promise 已经临近,但是,这样会更简洁:无需定义新函数,也无需金字塔形状。

注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, ...) { }

【问题讨论】:

标签: javascript node.js asynchronous callback


【解决方案1】:

这就是你已经可以用 js 做的事情了:

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

注意 asyncFunc[2,3] 必须是真正的 async...

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2017-03-30
    • 2018-12-20
    • 1970-01-01
    相关资源
    最近更新 更多