JavaScript 如何理解回调函数和回调地狱
JavaScript是一种流行的轻量级、解释性编译客户端脚本语言。大多数网络应用程序在客户端使用JavaScript。通过提供JavaScript的运行环境,它也可以在服务器端使用(Node.js)。本文将介绍回调函数和回调地狱。
回调函数: 回调函数是作为参数传递给另一个函数的函数,根据结果执行回调函数。它们基本上是在产生结果后才执行的函数。回调函数是异步JavaScript的重要组成部分。
示例: 这个示例展示了JavaScript中的回调函数。
Javascript
// Main function
const mainFunction = (callback) => {
setTimeout(() => {
callback([2, 3, 4]);
}, 2000)
}
// Add function
const add = (array) => {
let sum = 0;
for(let i of array) {
sum += i;
}
console.log(sum);
}
// Calling main function
mainFunction(add);
输出:
9
解释: 这里我们在mainFunction中使用setTimeout来模拟一些I/O操作或请求调用。传递的回调函数用于对数组元素求和。2秒后,打印出数组的总和,即9。
回调地狱: 回调地狱实际上是将嵌套的回调堆叠在一起形成金字塔结构。每个回调都依赖/等待前一个回调,从而形成了一个影响代码可读性和可维护性的金字塔结构。
示例: 在下面的示例中,我们将单词GeeksForGeeks拆分为三个单独的单词,并尝试依次动画显示每个单词。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Callback Hell</title>
<style>
* {
padding: none;
margin: none;
box-sizing: border-box;
}
.word {
color: #308d46;
font-size: 4rem;
transition: all .5s ease-in;
margin: 0 5px;
transform: translateY(3.8rem);
opacity: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
width: 95vw;
height: 95vh;
}
.container {
overflow: hidden;
display: flex;
flex-direction: row;
}
.animate {
opacity: 1;
transform: translateY(0);
}
</style>
</head>
<body>
<div class="container">
<h2 class="word">Geeks</h2>
<h2 class="word">For</h2>
<h2 class="word">Geeks</h2>
</div>
</body>
<script>
let words = document.querySelectorAll(".word");
const animateAll = (animate) => {
setTimeout(() => {
animate(words[0]);
setTimeout(() => {
animate(words[1]);
setTimeout(() => {
animate(words[2]);
}, 1000)
}, 1000)
}, 1000)
}
const animate = (word) => {
word.classList.add("animate");
}
animateAll(animate);
</script>
</html>
输出: 我们可以注意到animateAll函数采用金字塔结构,这使得它很难阅读。
参考: https://developer.mozilla.org/zh-CN/docs/Glossary/Callback_function