【发布时间】: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, ...) { }
【问题讨论】:
-
mm... 这正是 Promises 所做的... developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
-
欢迎来到 SO。请访问help center 了解询问内容和方式。您的问题与 SO 无关,但可能在 codereview 或 JS 论坛上有效
-
JavaScript 有
async函数:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript node.js asynchronous callback