콜백 지옥이란 함수의 매개변수로 넘겨지는 콜백 함수가 반복되어 코드의 들여쓰기 수준이 감당하기 힘들어질 정도로 깊어지는 현상이다.
|
document.write("<hr/>출근 과정 : ")
gotoWork("일어나고", function(message){
gotoWork("세면하고", function(message){
gotoWork("식사하고", function(message){
gotoWork("양치하고", function(message){
gotoWork("환복하고", function(message){
console.log('출근완료');
document.write('출근완료 ');
});
});
});
});
});
|
비동기식 작업을 차례대로 동기식으로 수행할 경우에 콜백지옥에 빠질 수 있습니다.
ex06.html 파일을 다음과 같이 만듭니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>콜백 지옥 (Callback Hell)</title> <script> let showMessage = (message, callback)=>{ console.log(message); document.write(message + ' ') callback(message) console.log(message); document.write(message + ' ') } function double(data, callback){ let n = data * 2; console.log(`n = ${n}`); callback(n); } function gotoWork(work, callback){ console.log(work); document.write(work + ' => ') callback(work) } window.onload = function () { showMessage("5", function(message){ showMessage("4", function(message){ showMessage("3", function(message){ showMessage("2", function(message){ showMessage("1", function(message){ console.log('0'); document.write('0 '); }); }); }); }); }); double(1, function(result){ double(result, function(result){ double(result, function(result){ double(result, function(result){ double(result, function(result){ double(result, function(result){ console.log("계산 완료!!!!"); }); }); }); }); }); }); document.write("<hr/>출근 과정 : ") gotoWork("일어나고", function(message){ gotoWork("세면하고", function(message){ gotoWork("식사하고", function(message){ gotoWork("양치하고", function(message){ gotoWork("환복하고", function(message){ console.log('출근완료'); document.write('출근완료 '); }); }); }); }); }); } </script> </head> <body> <h2>콜백 지옥 (Callback Hell)</h2> 콜백 지옥이란 함수의 매개변수로 넘겨지는 콜백 함수가 반복되어 코드의 들여쓰기 수준이 감당하기 힘들어질 정도로 깊어지는 현상이다. 비동기식 작업을 차례대로 수행할 경우에 콜백지옥에 빠질 수 있습니다. <hr> </body> </html> | cs |
실행 결과 입니다.

'Front End > Javascript' 카테고리의 다른 글
| Hook 이란? (3) | 2024.11.06 |
|---|---|
| [JavaScript] 배열에서 최대값/최소값 구하기 (0) | 2024.11.01 |
| [JavaScript] call() & apply() & bind()의 사용 2 (0) | 2024.10.24 |
| [JavaScript] call() & apply() & bind()의 사용 (0) | 2024.10.24 |
| [JavaScript] 콜백(Callback) 함수 5(this 문제점) (1) | 2024.10.24 |