Callbacks Concept
What is Callback?
JavaScript์์ ํจ์(function)์ ์ผ๊ธ ๊ฐ์ฒด์.
์ฆ, ํจ์๋ object type์ด๋ฉฐ ๋ค๋ฅธ ์ผ๊ธ ๊ฐ์ฒด์ ๋๊ฐ์ด ์ฌ์ฉ๋ ์ ์์
function ์์ฒด๊ฐ object์ด๋ฏ๋ก
๋ณ์์์ ๋ด์ ์๋ ์๊ณ ,
์ธ์๋ก์ ๋ค๋ฅธ ํจ์์ ์ ๋ฌ ํด ์ค์๋ ์๊ณ ,
ํจ์์์ ๋ง๋ค์ด์ง ์๋ ์๊ณ ,
๋ฐํ ๋ ์๋ ์์
Callback
: an asynchronous equivalent for a function
Callback Function
: ํน์ ํจ์์ ๋งค๊ฐ๋ณ์๋ก์ ์ ๋ฌ๋ ํจ์
-> Callback function์ ๊ทธ ํจ์๋ฅผ ์ ๋ฌ๋ฐ์ ํจ์์์์ ํธ์ถ๋๊ฒ ๋๋ค!
ex)
$("#btn_1").click(function() {
alert("Btn 1 Clicked!")
});
click method์ ์ธ์๊ฐ ๋ณ์๊ฐ ์๋๋ผ ํจ์์
click method์ ์ธ์๊ฐ ๋ฐ๋ก Callback Function!
Node.js์์ ์ด๋ฌํ Callback ํจ์๊ฐ ๋งค์ฐ ๋ง์ด ์ฌ์ฉ๋๋ค!
Blocking Code
Callback ํจ์๊ฐ ์ฌ์ฉ๋์ง ์๋
Blocking code
๋ง ๊ทธ๋๋ก ์ด๋ค ์์ ์ ์คํํ๊ณ ๊ธฐ๋ค๋ฆฌ๋ฉด์ ์ฝ๋๊ฐ ๋งํ๊ฒ ๋จ!
ex)
input.txt file
Let's understand what is a callback function.
What the HELL is it?
blocking.js
var fs = require("fs");
var data = fs.readFileSync('input.txt')
console.log(data.toString());
console.log("Program has ended!")
Result
$ node blocking.js
Let's understand what is a callback function.
What the HELL is it?
Program has ended!
text๋ฅผ ์ถ๋ ฅํ๊ณ program ์ข ๋ฃ message ์ถ๋ ฅ๋จ
Non-Blocking Code
Callback ํจ์๊ฐ ์ฌ์ฉ๋
Non-Blocking Code
ํจ์๊ฐ ์คํ๋ ๋, ํ๋ก๊ทธ๋จ์ด ํจ์๊ฐ ๋๋ ๋๊น์ง ๊ธฐ๋ค๋ฆฌ์ง ์๊ณ ๋ฐ๋ก ๊ทธ ์๋์ ์๋ code๋ค์ ์คํํจ
๊ทธ ๋ค์ ํจ์์ ์๋ ์์ ์ด ๋ค ๋๋๋ฉด callback ํจ์๋ฅผ ํธ์ถํจ
ex)
input.txt๋ blocking code ์์์ ๊ฐ์ file ์ฌ์ฉ
non-blocking.js
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program has ended");
๋ชจ๋ Node application์ ๋น๋๊ธฐ์ ํจ์์์๋ ์ฒซ๋ฒ์งธ parameter๋ก๋ error๋ฅผ, ๋ง์ง๋ง parameter๋ก๋ callback ํจ์๋ฅผ ๋ฐ์
fs.readFile()
ํจ์๋ ๋น๋๊ธฐ์์ผ๋ก ํ์ผ์ ์ฝ๋ ํจ์๋์ค์ ์๋ฌ๊ฐ ๋ฐ์ํ๋ฉด err ๊ฐ์ฒด์ error ๋ด์ฉ์ ๋ด๊ณ ,
๊ทธ๋ ์ง ์์์์๋ ํ์ผ ๋ด์ฉ์ ๋ค ์ฝ๊ณ ์ถ๋ ฅํจ!
Result
$ node non-blocking.js
Program has ended
Let's understand what is a callback function.
What the HELL is it?
readFile()
method๊ฐ ์คํ ๋ ํ, program์ด method๊ฐ ๋๋ ๋๊น์ง ๋๊ธฐํ์ง ์๊ณ ๊ณง๋ฐ๋ก ๋ค์ ๋ช ๋ น์ด๋ก ์งํํ์๊ธฐ ๋๋ฌธ์, program์ด ๋๋ฌ๋ค๋ message๋ฅผ ์ถ๋ ฅ ํ ํ์, text ๋ด์ฉ์ ์ถ๋ ฅํจ๊ทธ๋ ๋ค๊ณ program์ด ๋๋๊ณ ๋์ text ๋ด์ฉ์ ์ถ๋ ฅํ ๊ฒ์ ์๋!
program์ด ์ค์ง์ ์ผ๋ก ๋๋๊ฑด text๊ฐ ์ถ๋ ฅ๋ ํ ์ด๋ค!
๋ง์ฝ์
readFile()
๋ค์์ ์คํ๋๋ ์ฝ๋๊ฐ ๊ทธ๋ฅconsole.log()
๊ฐ ์๋๋ผreadFile()
๋ณด๋ค ์์ ์๊ฐ์ด ์ค๋๊ฑธ๋ฆฌ๋ ์ฝ๋์๋ค๋ฉด text๋ฅผ ๋จผ์ ์ถ๋ ฅํ๊ฒ ๋ ๊ฒ!
Wrap-up
Callback ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ์ด๋ ๊ฒ program์ ํ๋ฆ์ ๋์ง ์์์ผ๋ก์จ, non-blocking code๋ฅผ ์ฌ์ฉํ๋ server๋ blocking code๋ฅผ ์ฌ์ฉํ๋ server ๋ณด๋ค ๋ ๋ง์ ์์ ์์ฒญ์ ๋น ๋ฅด๊ฒ ์ฒ๋ฆฌํ ์ ์๊ฒ ๋๋ค!
Last updated
Was this helpful?