在一个HTML文档中,当页面加载时,脚本会被运行,JS定义了一系列链锁在一起的函数,每当前一个函数被调用时,所有函数都会被调用。done
. 我对这个例子有很多疑问。
- 为什么
f1
未定义? - 我是否应该能够定义函数
f1
, …,f4
也在callbacksInit
以免污染全局命名空间? - 我是否应该能够定义函数
f1
, …,f4
在JS文档中,在callbacksInit
?
var f1 = function() { console.log("Running f1"); }
var f2 = function() { console.log("Running f2"); }
var f3 = function() { console.log("Running f3"); }
var f4 = function() { console.log("Running f4"); }
function callbacksInit() {
function start() {
f1()
.done(f2)
.done(f3)
.done(f4);
}
start();
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="./callbacks.js"></script>
</head>
<body onload="callbacksInit()">
<main>
<h1>CALLBACKS ASYNC</h1>
</main>
</body>
</html>
解决方案:
一个函数本身并不返回任何东西,所以才会有一个 “函数”。undefined
const a = () => {
console.log("Running f1");
}
// returns "undefined"
const b = () => {
console.log("Running f1");
return 'b';
}
// returns "b"
另外 根本就没有 done()
除了jQuery的延迟模式但要使用它,你需要使用jQuery,这不是在标签中的
你需要返回一个 Promise
对象
function a() {
return new Promise( function(resolve, reject) {
// now you can either:
// return resolve('data')
// return reject(new Error('My error message'))
});
}
通过返回一个承诺,你现在可以使用正常的回调地狱🤦♂️。
function callbacksInit() {
function start() {
f1()
.then(function(data1) { f2() })
.then(function(data2) { f3() })
.then(function(data3) { f4() })
.then(function(data4) { /* done, continue here */ })
.catch(function(err) {
console.log(err.message) // the message of the error upon reject()
});
}
start();
}
或使用asyncawait
function callbacksInit() {
function async start() {
try { // there's no "catch" in async/await so we wrap all in try/catch
var data1 = await f1()
var data2 = await f2()
var data3 = await f3()
var data4 = await f4()
} catch(err) {
console.log(err.message) // the message of the error upon reject()
}
}
start();
}
重要提示
总是返回一个 Error
拒绝诺言时的对象,会让你今后的事情变得简单很多😁。