์ด๋ฒ ์๊ฐ์๋ ๋น๋๊ธฐ์ ์ฌ์ฉํ๋ promise์ ๋ํด ๋ฐฐ์ ๋ค.
์ ์ ์ด๋ก ์ด ๊น์ด์ ธ ๊ฐ๋ค..
.then
, .catch
๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๋ค.then
์ผ๋ก ์ ๋ฌ๋ ์ฝ๋ฐฑํจ์๊ฐ ํธ์ถ๋๋ค.์ฝ๋ฐฑ ํจ์์ ๊ฒฐ๊ณผ ๊ฐ์ด ์์ ๊ฒฝ์ฐ ์ฒซ๋ฒ์งธ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ์ ์ ์๋ค.
catch
๋ก ์ ๋ฌ๋ ์ฝ๋ฐฑํจ์๊ฐ ์คํ๋๋ค.์ฝ๋ฐฑํจ์๋ ํ๋ผ๋ฏธํฐ๋ก ์ ๋ฌ๋๊ณ ๊ทธ ์ดํ๋ฅผ ์๋ ค์ค๋ค.
fech('...');
.then(function(response ๊ฐ์ฒด){
//์ฑ๊ณต ์ฝ๋
})
.catch(function(response ๊ฐ์ฒด){
//์คํจ ์ฝ๋
})
promise
๋ฅผ ๋ฐํํ๋ค.promise
์ state
์ ์๊ด์์ด ์ฆ์ ์ข
๋ฃํ๋ค.const promiseAll = Promise.all([promise1, promise2, ...])
promiseAll.then((result) => {
console.log(resulte)
})
promise โค (then) โค response.joson() โค (then) โค Result
response.json()
โค promise๋ก ๋ฆฌํดํ๋ค.(์ด๋ฏธ JSON ํ ์คํธ ํ์ผ์)
promise
์ฝ๋๋ฅผ ๊ฐ๊ฒฐํ๊ฒ ์์ฑํด ์ค ์ ์๋ค.async
ํค์๋๋ฅผ ์ฌ์ฉํ๊ณ ,await
ํค์๋๋ฅผ ์ฌ์ฉํ๋ค.await
ํค์๋๊ฐ ์์ฑ๋ ์ฝ๋๊ฐ ์คํ ํ ๋ค์ ์์์ ์ฝ๋๊ฐ ์คํ๋๋ค.async
ํจ์๋promise
๋ฅผ ๋ํ๋ธ๋ค.//์ ์ธ์
async function func(){
await ์คํ ์ฝ๋
}
//ํํ์
const func = async function(){
await ์คํ ์ฝ๋
}
//ํ์ดํ ํจ์
const func = asyn() => {
await ์คํ ์ฝ๋
}
await
๋ ํจ์ ๋ด๋ถ์ ์กด์ฌ ํด์ผํ๋ฉฐasync
๊ฐ ํจ์ ์์ ์์ฑ ๋ผ์ผํ๋ค.
async
๋ง๋ฌด๋ฆฌํ๊ณ ์ถ์ ๊ฒฝ์ฐ ํด๋น ํจ์ ๋ค์ .then()
์ ๋ถ์ฌ์ค๋ค.func().then();
fs(File System) : PC์ ํ์ผ์ ์ฝ๊ฑฐ๋ ์ ์ฅํ๋ ์ผ์ ํ ์ ์๊ฒ ๋์์ค๋ค.
readFile : ํ์ผ ์ฝ์ ๋ ์ฌ์ฉํ๋ ๋ฉ์๋
writeFile : ํ์ผ ์ ์ฅํ ๋ ์ฌ์ฉํ๋ ๋ฉ์๋
require : Node.js์์ ๋ค๋ฅธ ํ์ผ ๋ถ๋ฌ์ค๋ ๊ตฌ๋ฌธ
const fs = require('fs'); // ํ์ผ ์์คํ
๋ชจ๋ ๋ถ๋ฌ์ค๊ธฐ
const dns = require('dns'); // DNS ๋ชจ๋ ๋ถ๋ฌ์ค๊ธฐ
ํด๋น ํ๋ก๊ทธ๋๋ฐ ์ธ์ด์์ ๊ณต์์ ์ผ๋ก ์ ๊ณตํ๋ ๋นํธ์ธ ๋ชจ๋(built-in module)์ด ์๋, ๋ชจ๋ ์ธ๋ถ ๋ชจ๋์ ์ผ์ปซ๋๋ค.
Node.js์์ 'underscore'์ Node.js ๊ณต์๋ฌธ์์๋ ์๋ ๋ชจ๋๋ก ์๋ธ ํํฐ ๋ชจ๋์ด๋ค.
๋ชจ๋ ๋ค์ด๋ก๋๋ฅผ ์ํด npm
์ ์ฌ์ฉํ๋ค.
npm install : ๋ชจ๋ ์ค์น
fs.readFile(path, [options], callback)
path\<String>,\<Buffer>,\<URL>,\<integer>
<string>
ํ์
์ ๋ฐ๋๋ค.options\<Object>\<String>
options
๋ ๋ฃ์ ์๋, ๋ฃ์ง ์์ ์๋ ์๋ค.utf8
)// ./etc/file ํ์ผ ๋ถ๋ฌ์ค๊ธฐ
fs.readFile('./etc/file','','');
//utf8์ ์ด์ฉํด ์ฝ๋๋ค.
fs.readFile('./etc/file', 'utf8', ...)
//etc ํ์ผ options์ด์ฉํด ์ฝ๊ธฐ
let options = { encoding : 'utf8', flag : 'r' };
callbak\<function>
err\<Error>\<AggregateError>
err
๋ null
์ด๋๋ค.data\<String>\<Buffer>
Buffer
๋ผ๋ ๊ฐ์ฒด๊ฐ ์ ๋ฌ ๋๋ค.(data
๋ ํ์ผ์ ๋ด์ฉ)fs.readFile('test.txt', 'utf8', (err, data) => {
if(err){
thow err;
}
console.log(data);
})
promise
๋ฅผ ์ด์ฉํด ์ฝ๋ฐฑ ์ง์ฅ์ ๋ฒ์ด๋ ์ ์์ผ๋ฉฐ
then
, catch
๋์ Async
, Awit
๋ฅผ ์ฌ์ฉํด ๊ธ์ ๊ฐ๊ฒฐํ๊ฒ ์์ฑํ ์ ์๋ค.
์ด๋ฒ ๊ณผ์ ๋ฅผ ๊ฝค ์ด๋ ค์ ๋ค. ๋คํํ ๋ค์๋ ๊น์ง ์งํํ๋ ๊ฑฐ๋ผ ๋คํ์ด์๋ค.
์ปค๋ฆฌํ๋ผ ๋ง์ง๋ง ์๊ฐ์๋ ์ ์ง์ ์ ๋ฐฐ ์ฐธ๊ฒฌ ์์ ์ผ๋ก
์ฌ๋ฌ ์๊ธฐ๋ฅผ ํ๋ฉด์ ๋์ ๋ฐฉํฅ์ฑ์ ์ ์ ์์๋ ๋ป ๊น์ ์๊ฐ์ด์๋ค.