是否有Javascript指令可以避免异步回调地狱? 类似于"如果那么其他"我想象一下"然后"。 例如,假设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, ...) { }
答案 0 :(得分:1)
那你已经可以用js做什么了:
Traceback (most recent call last):
File "t.py", line 5, in <module>
d = webdriver.Chrome(chrome_options=chop)
File "/home/t/env/lib/python3.5/site-packages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__
keep_alive=True)
File "/home/t/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 89, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/home/t/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 138, in start_session
'desiredCapabilities': desired_capabilities,
File "/home/t/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 195, in execute
self.error_handler.check_response(response)
File "/home/t/env/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 170, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.30.477691 (6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-21-generic x86_64)
请注意,asyncFunc [2,3]必须是 async ...