๐ค TIL(Today I Learned)
TIL(20210727) - ๋น๋๊ธฐ(callback, promise, asyncAwait)
Seungjae Lee
2021. 7. 27. 22:26
๐ Today
- javascript ๋น๋๊ธฐ ํธ์ถ, callback ํ์ต
- Promise, async/await ํ์ต
- Node.js ๋ด์ฅ๋ชจ๋ ์ฌ์ฉ๋ฒ ํ์ต
๐ค Learned
๋น๋๊ธฐ ์ฝ๋ฐฑํจ์ ์ฌ์ฉ๋ฒ
const delay = (wait, callback) => {
setTimeout(callback, wait);
}
function runCallback() {
resetTitle();
playVideo();
delay(1000, () => {
pauseVideo();
displayTitle();
delay(500, () => {
highlightTitle();
delay(2000, resetTitle);
});
});
}
Promise ์ฌ์ฉ๋ฒ
const sleep = (wait) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('hello');
}, wait);
});
};
// const sleep = (wait) => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// reject(new Error('์๋ฌ'));
// }, wait);
// });
// };
function runPromise() {
resetTitle();
playVideo();
sleep(1000)
.then((param) => {
console.log(param);
pauseVideo();
displayTitle();
return "world!!!" + param;
})
.then((param) => {
console.log(param);
sleep(500);
})
.then(highlightTitle)
.then(sleep.bind(null, 2000))
.then(resetTitle)
.catch(err => {
console.log(err);
})
}
async/await ์ฌ์ฉ๋ฒ
async function runAsync() {
resetTitle();
playVideo();
await sleep(1000);
pauseVideo();
displayTitle();
await sleep(500);
highlightTitle();
await sleep(2000);
resetTitle();
}
Node.js - fs ๋ชจ๋ ์ฌ์ฉ๋ฒ
const fs = require('fs');
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
throw err; // ์๋ฌ๋ฅผ ๋์ง๋๋ค.
}
console.log(data);
});
๋น๋๊ธฐ ํธ์ถ์ ๋ํด ํ์ตํ๋ฉด์ ๋๋ ์
๋ง์ด ๋ณต์กํ๊ณ ์ด๋ ต์ง๋ง ์ด์ ์ผ ์ ๋๋ก ๋ ํ๋ก๊ทธ๋๋ฐ์ ๋ฐฐ์ฐ๋ ๊ฒ ๊ฐ๋ค.
๋ณต์ต์ ํ์คํ๊ฒ ํ์ง ์๊ณ ๋์ด๊ฐ๋ค๋ฉด ๋์ค์ ๋ง์ด ํ๋ค์ด์ง ๊ฒ ๊ฐ์ ํํธ๋ค.
+ ์๋ฃ๊ตฌ์กฐ ๊ณต๋ถ ๋ฏธ๋ค๋ ๊ฒ ํด์ผ ํ๋๋ฐ ์ด๋ฒ ์ฃผ ์ค์ ํด๊ฒฐ ํด์ผ ํ ๊ฒ ๊ฐ๋ค.
๐ Tomorrow
- ๋น๋๊ธฐ ๋ณต์ต
- ํ ์ด, ์๋ฃ๊ตฌ์กฐ ๋ฐ๋ฆฐ ๊ฒ ์กฐ๊ธ์ฉ ํ๊ธฐ