해당글은 오늘 공부한 내용을 정리하여 메모하는 형식으로 작성한 것으로 설명이나 이해를 돕는 글이 아님을 명시합니다.
callback 실행 상황
blocking
non-blocking
비동기 함수 전달 패턴
/* callback 패턴 */
let request= 'coffee'
orderCofffeeAsync(request, function(res){
drink(res)
})
/* 이벤트 등록 패턴 */
let request= 'coffee'
orderCofffeeAsync(request).onready = function(res){
drink (res)
}
const printString = (string)=>{
setTimeout(function () {
console.log("callback ", string);
}, Math.floor(Math.random() * 100) + 1);
};
const printAll = () => {
printString("A");
printString("B");
printString("C");
};
printAll();
// callback 사용
const printString = (string, callback) =>{
setTimeout(function () {
console.log("callback ", string);
callback();
}, Math.floor(Math.random() * 100) + 1);
};
const printAll = () => {
printString("A", ()=> {
printString("B", ()=>{
printString("C", ()=> {
});
});
});
};
printAll();
error handling
const somethingHappen = (callback) => {
waitingUtilSomethingHappens()
if(isGood){
callback(null,something)
}
if(isBad){
callback(something, null)
}
}
// 사용 예제
somethingHappen((err, data)=> {
if(err){
console.log('Err')
return;
}
return data;
})
const printString = (string) => {
return new Promise((resolve, reject) => {
setTimeout(() =>{
console.log(string);
resolve();
}, Math.floor(Math.random() * 100) + 1);
})
};
const printAll = () => {
printString("A")
.then(()=>{
return printString("B")
})
.then(()=>{
return printString("C")
})
};
printAll();
Primise Hell
return
처리를 잘 하면(promise chaining) 어느 정도 처리 가능하지만 그렇지 않으면 얼마든지 hell을 경험 할 수 있다.function gotoCode1(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('1. first')}, 100)
})
}
function gotoCode2(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('2. Second')}, 400)
})
}
function gotoCode3(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('3. Third')}, 300)
})
}
function gotoCode4(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('4. Forth')}, 200)
})
}
gotoCode1()
.then(data=>{
console.log(data);
gotoCode2()
.then(data=> {
console.log(data)
gotoCode3()
.then(data=> {
console.log(data)
gotoCode4()
.then(data=> {
console.log(data)
})
})
})
})
function gotoCode1(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('1. first')}, 200)
})
}
function gotoCode2(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('2. Second')}, 500)
})
}
function gotoCode3(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('3. Third')}, 100)
})
}
function gotoCode4(){
return new Promise((resolve, reject) => {
setTimeOut(()=>{ resolve('4. Forth')}, 300)
})
}
const result = async () => {
const one = await gotoCode1()
console.log(one);
const two = await gotoCode2()
console.log(two);
const three = await gotoCode3()
console.log(three);
const four = await gotoCode4()
console.log(four);
}
result();
일정 시간 후에 함수를 실행
setTimeout(function () {
console.log('1초 후 실행');
}, 1000);
// 123
일정 시간의 간격을 가지고 함수를 반복적으로 실행
setInterval(function () {
console.log('1초마다 실행');
}, 1000);
// 345
반복 실행중인 타이머를 종료
const timer = setInterval(function () {
console.log('1초마다 실행');
}, 1000);
clearInterval(timer);
// 더 이상 반복 실행되지 않음
// 123
모듈이란?
건축으로부터 비롯된 모듈이라는 단어는, 어떤 기능을 조립할 수 있는 형태로 만든 부분이다. fs(File System) 모듈은, PC의 파일을 읽거나 저장하는 등의 일을 할 수 있게 도와준다.
<script>
태그를 이용했지만 Node.js 에서는 자바스크립트 코드 가장 상단에 require
구문을 이용하여 다른 파일을 불러옵니다.const fs = require('fs'); // 파일 시스템 모듈을 불러옵니다
const dns = require('dns'); // DNS 모듈을 불러옵니다
path \<string> | \<Buffer> | \<URL> | \<integer>
fs.readFile('/etc/passwd', ..., ...)
options \<Object> | \<string>
let options = {
encoding: 'utf8', // UTF-8이라는 인코딩 방식으로 엽니다
flag: 'r' // 읽기 위해 엽니다
}
// /etc/passed 파일을 옵션을 사용하여 읽습니다.
fs.readFile('/etc/passwd', options, ...)
callback \<Function>
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
throw err; // 에러를 던집니다.
}
console.log(data);
});
fetch(url)
.then((response) => response.json()) // 자체적으로 json() 메소드가 있어, 응답을 JSON 형태로 변환시켜서 다음 Promise로 전달합니다
.then((json) => console.log(json)) // 콘솔에 json을 출력합니다
.catch((error) => console.log(error)); // 에러가 발생한 경우, 에러를 띄웁니다
추가적으로 스터디 필요한 것
- 브라우저의 비동기 함수 작동원리(이벤트 루프)