콜백지옥

:연속된 비동기함수를 처리할때 콜백이 계속 깊어지는 현상 

Promise 

비동기의 콜백 지옥을 해결해주는 방법

 

Pending(대기상태)

(resolve)-->1. Fulfilled(성공)

(reject)--> 2.Rejected(실패)

function isPositive(number,resolve,reject){
  setTimeout(()=>{
    if(typeof number==='number'){
      //성공 ->resolve
      resolve(number>=0? "양수":"음수")
    }else{
      //실패 ->reject
      reject("주어진 값이 숫자형 값이 아닙니다.")
    }
  },2000)
}

isPositive(
  10,
  (res)=>{
  console.log("성공적으로 수행함:",res);
  },
  (err)=>{
  console.log("실패하였음:",err)
  }
);

#성공

function isPositive(number,resolve,reject){
  setTimeout(()=>{
    if(typeof number==='number'){
      //성공 ->resolve
      resolve(number>=0? "양수":"음수")
    }else{
      //실패 ->reject
      reject("주어진 값이 숫자형 값이 아닙니다.")
    }
  },2000)
}

isPositive(
  [],
  (res)=>{
  console.log("성공적으로 수행함:",res);
  },
  (err)=>{
  console.log("실패하였음:",err)
  }
);

#실패 

 

 

Promise

function isPositive(number, resolve, reject){
  setTimeout(()=>{
    if (typeof number ==="number"){
      resolve(number >= 0?"양수":"음수");
    } else {
      reject("주어진 값이 숫자형 값이 아닙니다.");
    }
  },2000);
}

function isPositiveP(number){
  const executor =(resolve, reject)=> {
    setTimeout(()=>{
      if (typeof number ==="number"){
        console.log(number);
        resolve(number >= 0?"양수":"음수");
      } else {
        reject("주어진 값이 숫자형 값이 아닙니다.");
      }
    },2000);
  };
  const asyncTask = new Promise(executor);
  return asyncTask;
}

const res= isPositiveP(101);

res
  .then((res)=>{
    console.log("작업성공:", res);
  })
  .catch((err)=>{
    console.log("작업실패: ",err);
  });

 

Promise 사용 X

function taskA(a,b,cb){
  setTimeout(()=>{
    const res= a+b;
    cb(res);
  },3000)
}

function taskB(a,cb){
  setTimeout(()=>{
    const res= a*2;
    cb(res);
  },1000)
}

function taskC(a,cb){
  setTimeout(()=>{
    const res =a *-1;
    cb(res);
  },2000)
}

taskA(3,4,(a_res)=>{
  console.log("taskA:",a_res);
  taskB(a_res,(b_res)=>{
    console.log("task B:",b_res);
    taskC(b_res,(c_res)=>{
      console.log("task C:",c_res);
    });
  });
});

 

Promise 사용

function taskA(a, b) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = a + b;
      resolve(res);
    }, 3000);
  });
}

function taskB(a) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = a * 2;
      resolve(res);
    }, 1000);
  });
}

function taskC(a) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const res = a * -1;
      resolve(res);
    }, 2000);
  });
}

taskA(5, 1)
.then((a_res) => {
  console.log("A RESULT:", a_res);
  return taskB(a_res);
})
.then((b_res)=>{
  console.log("B RESULT:",b_res);
  return taskC(b_res);
})
.then((c_res)=>{
  console.log("C RESULT:",c_res);
});

==> 콜백지옥을 사라지게 함. 더 객관적이고 쉽게 할 수 있게 함 .

 

'개발 > javascript' 카테고리의 다른 글

[javascript]가비지 컬랙션  (0) 2024.03.14
[javascript]async & await  (0) 2023.07.26
[javascript]동기&비동기  (0) 2023.07.24
[javascript]응용  (0) 2023.07.23
[javascript] 응용1  (0) 2023.07.04

동기방식

<자바스크립트의 싱글 스레드 작업 수행 방식> 

Thread -task A - taskB - taskC

자바스크립트는 코드가 작성된 순서대로 작업을 처리함

이전 작업이 진행 중 일때는 다음 작업을 수행하지 않고 기다림 

먼저 작성된 코드를 먼저 다 실행하고 나서 뒤에 작성된 코드를 실행한다. 

--> 동기 방식의 처리 

 

동기적 처리의 단점은 하나의 작업이 너무 오래 걸리게 될 시, 

모든 작업이 오래걸리는 하나의 작업이 종료되기 전 까지 올 스탑 되기 때문에, 전반적인 흐름이 느려진다. 

--> 동기처리 방식의 문제점 

 

코드를 실행하는 일꾼인 Thread를 여러개 사용하는 방식인 MultiThread 방식으로 작동시키면 이런 식 으로 작업 분할이 가능하다. 

오래 걸리는 일이 있어도 다른 일꾼 Thread에게 지시하면 되므로 괜찮다. 

 

그러나 자바스크립트는 싱글 쓰레드로 동작한다. 

즉 이런 방식으로 일꾼을 여러개 사용하는 방법 상용이 불가함. 

 

싱글 쓰레드 방식을 이용하면서 동기적 작업의 단점을 극복하기 위해 여러 개의 작업을 동시에 실행시킨다. 

즉, 먼저 작성된 코드의 결과를 기다리지 않고 다음 코드를 바로 실행한다. 

-->비동기 처리 방식

 

function taskA(){
  console.log("A 작업 끝");
}
taskA();
console.log("코드 끝");
#동기적 방식
function taskA(){
  setTimeout(()=>{
    console.log("A TASK END");
  },2000);
}
taskA();
console.log("코드 끝");
#비동기적방식

**복습다시합시다... 

'개발 > javascript' 카테고리의 다른 글

[javascript]async & await  (0) 2023.07.26
[javascript]Promise & 콜백지옥  (0) 2023.07.25
[javascript]응용  (0) 2023.07.23
[javascript] 응용1  (0) 2023.07.04
[javascript]기본정리5  (0) 2023.07.03

비 구조화 할당 

let arr=["one","two","three"]

let one = arr[0];
let two = arr[1];
let three =arr[2];

console.log = arr[2];

==>

let arr=["one","two","three"]

let [ one, two, three] =arr;

console.log(one, two, three);

비구조화 할당은 배열의 순서에 따라 할당할 수 있게 하는 것이다. 

 

SWAP

let a =10;

let b=20;

[a,b]=[b,a]
console.log(a,b)

객체에서의 비구조화 할당

let object ={one: 'one',two:'two',three:'three'};

let one=object.one;
let two=object.two;
let three=object.three;

console.log(one,two,three);
==> 이러한 방법은 객체의 이름을 계속반복해야 하는 단점이 존재한다. 


let object ={one: 'one',two:'two',three:'three'};

let {one, two, three}=object;
console.log(one,two,three);
순서와는 상관없이 키값을 이용해서 적용한다. 


키값으로 구조화를 할당하지만 다른 이름을 사용하고 싶다면 
let {name: myname, one, two }이런식으로 사용하면된다.

spread 연산자 

const cookie= {
  base:"cookie",
  madeIn:"korea"
};

const chocohipCookie={
  ...cookie,
  toping: "chocochup"
}

const blueberryCookie={
  ...cookie,
  toping: "chocochup"
}

const strawberryCookie={
  ...cookie,
  toping: "chocochup"
}
...: spread 연산자 
중복된 내용을 생략해준다.

활용

const noTopingCookies =["촉촉한쿠키","안촉촉한쿠키"];
const topingCookies = ["바나나쿠키","블루베리쿠키","딸기쿠키","초코칩쿠키"];

const allCookies =[...noTopingCookies,...topingCookies];
console.log(allCookies);

'개발 > javascript' 카테고리의 다른 글

[javascript]Promise & 콜백지옥  (0) 2023.07.25
[javascript]동기&비동기  (0) 2023.07.24
[javascript] 응용1  (0) 2023.07.04
[javascript]기본정리5  (0) 2023.07.03
[javascript]기본정리4  (0) 2023.07.02

Trusy and Falsy

참같은 값, 거짓같은 값

let a= "";

if (a){
  console.log("True");
} else{
  console.log("False");
} 

-->False

let a= "string";

if (a){
  console.log("True");
} else{
  console.log("False");
}

-->True

 

이러한 것들은javascipt의 자신만의 기준으로 True와 False를 나누는 Trusy와 Falsy에 의한 속성에 의한 결과이다. 

 

{ }, 123, "0", Infinity => True  :Trusy

null, undefined, 0, -0, NaN,""=>False: Falsy

 

const getName =(person) => {
  return person.name;
};

let person;
const name =getName(person);
console.log(name);

이렇게 person이라는 값이 undefined가 되면 error가 발생하는데 객체가 포함되어 있지 않아서 
점표기법을 사용할 수  없기 때문이다. 


const getName =(person) => {
  if (person===undefined||person ===null){
    return "객체x"
  }
  return person.name;
};

let person;
const name =getName(person);
console.log(name);

이런식으로 조건식을 사용하여 해결할 수 있다.
const getName =(person) => {
  if (!person){//false Not=>True
    return "객체x"
  }
  return person.name;
};

let person=null;
const name =getName(person);
console.log(name);

함수가 복잡해지고 많아질 수록 조건문을 사용하면 복잡해지기 때문에 Falsy속성을 활용해서 

해결 할 수 있었다. 

 

삼항연산자

(조건문 ? 참일때: 거짓일 때)

let a =-3;
a>=0? console.log("양수"):console.log("음수")

"a>0보다 크면 양수 아니면 음수"

let a =[];
a.length===0?console.log("빈배열"):console.log("안 빈 배열");

let a =[];
const arrayStatus= a.length===0?"빈배열":"안 빈 배열";
console.log(arrayStatus);

trusy falsy를 활용한 삼항연산자

let a=[];
const result =a? true: false;
console.log(result);

중첩을 활용한 삼항연산자

let score=60;

score>=90
?console.log("A+")
:score>=50
?console.log("B+")
:console.log("F")

단란회로평가

:논리연산자 활용한 문법

const getName =(person)=>{
  return person && person.name;
};

let person;
const name=getName(person);
console.log(name);

 

 

'개발 > javascript' 카테고리의 다른 글

[javascript]동기&비동기  (0) 2023.07.24
[javascript]응용  (0) 2023.07.23
[javascript]기본정리5  (0) 2023.07.03
[javascript]기본정리4  (0) 2023.07.02
[javascript]기본정리3  (0) 2023.07.02

배열 

let arr = new Array(); //생성자

let arr = []; //배열 리터럴

배열리터럴 방식에서는 대괄호[ ]를 사용한다

 

let arr = [1,"2",true,null,{}];

배열에서는 모든 자료형을 넣을 수 있다.

console.log(arr[0]);
console.log(arr[1]);
//read

index를 사용하면 배열의 각 위치에 해당하는 값을 확인 할 수 있다. 

arr.push(6)
arr.push({key:"value"})
console.log(arr);

push는 배열에 값을 추가해 주는 함수이다. push를 사용하면 값을 배열의 맨 끝에 추가해준다.

console.log(arr.length);

배열의 길이 확인

 

반복문

for (초기식; 조건식; 연산){ 반복 수행 명령 }

for(let i=1;i<=100;i++){
  //반복 수행할 명령 
  console.log("장도진")
}

 

반복문은 배열에서 더 유용하게 사용될 수 있다. 

const arr=['a','b','c']
for(let i=0;i<=100;i++){
  //반복 수행할 명령 
  console.log(arr[i])
}

객체에서 반복문 

//key 값 순회 

let person={
  name:"장도진",
  age:25,
  tall:186
};

const personKeys =Object.keys(person);

for(let i=0;i<personKeys.length; i++){
  console.log(personKeys[i]);
  
}

// key: value

let person={
  name:"장도진",
  age:25,
  tall:186
};

const personKeys =Object.keys(person);

for(let i=0;i<personKeys.length; i++){
  const curKey =personKeys[i];
  const curValue=person[curKey];

  console.log('${curKey}:${curValue}');
}

//value 순회

let person={
  name:"장도진",
  age:25,
  tall:186
};

const personValues =Object.values(person);

for(let i=0;i<personValues.length; i++){
  console.log(personValues[i]);
}

 

배열 내장 함수 

forEach

const arr=[1,2,3,4];

for (let i =0; i<arr.length;i++){
  console.log(arr[i]);
}



const arr=[1,2,3,4];
arr.forEach((elm)=>console.log(elm));

1.

const arr = [1,2,3,4];
const newArr=[];
arr.forEach(function(elm){
  newArr.push(elm*2);
});
console.log(newArr);

2.map

const arr = [1,2,3,4];
const newArr=arr.map((elm=>{
  return elm*2;
}))

console.log(newArr);

3.includes

const arr = [1,2,3,4];

let number=3;
arr.forEach((elm)=>{
  if(elm === number){
    console.log(true);
  }
});




const arr = [1,2,3,4];

let number=3;
console.log(arr.includes(number));

 

4.index

const arr = [1,2,3,4];

let number="3";
console.log(arr.indexOf(number));
//일치하지 않으면 -1을 출력 
//일치하면 해당하는 인덱스값을 출력

5.findIndex

const arr = [
  {color:"red"},
  {color:"black"},
  {color:"blue"},
  {color:"green"}
];
let number="3";
console.log(arr.findIndex((elm)=>elm.color==="red"));

6.find

const arr = [
  {color:"red"},
  {color:"black"},
  {color:"blue"},
  {color:"green"}
];
let number="3";
const element =arr.find((elm)=>{
  return elm.color ==="blue";
});

console.log(element);

7.filter

const arr = [
  {num:1,color:"red"},
  {num:2,color:"black"},
  {num:3,color:"blue"},
  {num:4,color:"green"}
];

console.log(arr.filter((elm)=>elm.color==="blue"))

8.slice

const arr = [
  {num:1,color:"red"},
  {num:2,color:"black"},
  {num:3,color:"blue"},
  {num:4,color:"green"}
];

console.log(arr.slice(0,2));

9.concat

const arr1 = [
  {num:1,color:"red"},
  {num:2,color:"black"},
  {num:3,color:"blue"},
];

const arr2= [
  {num:4,color:"green"},
  {num:5,color:"blue"},
];

console.log(arr1.concat(arr2));

10.sort

let chars=['나','다','가'];

chars.sort();

console.log(chars);





let numbers=[1,3,5,6,8,7,4];

const compare=(a,b)=>{
  if(a>b){
    return 1;
  }
  if(a<b){
    return -1;
  }
  return 0;
}
numbers.sort();

console.log(numbers);

11. join

const arr=["장도진","님","안녕하세요","반갑습니다."];
console.log(arr.join(" "));

'개발 > javascript' 카테고리의 다른 글

[javascript]응용  (0) 2023.07.23
[javascript] 응용1  (0) 2023.07.04
[javascript]기본정리4  (0) 2023.07.02
[javascript]기본정리3  (0) 2023.07.02
[javascript] 기본정리2  (0) 2023.07.01

객체

객체는 NonPrimitive Type의 객체에 해당한다. 

객체를 정의 하는 방식 

let person= new Object();
//객체 생성자 방식
let person1={};
//객체 리터럴방식

대부분의 개발자들은 객체 리터럴 방식을 선호한다.

let person={
  key:"value",//프로퍼티(객체 프로퍼티)
  key1:"value2",
  key2:true,
  key3: undefined,
  key4:[1,2],
  key5: function(){}

};
//객체 리터럴방식

console.log(person);

객체에 해당하는 하나하나를 프로퍼티라고하며 갯수는 상관이 없다.

그리고 value에는 함수나 배열 등 다양한 자료형을 넣을 수 있다.

key는 문자열로 작성해야하며 key끼리 중복이 가능하지만 원하는 값을 찾기 위해서 다르게 하는 것이 좋다 .

 

객체의 프로퍼티에 접근하는 방법

1. 점표기법 : 다음과 같이 객체에 . 을 사용하면 key에 해당하는 value를 얻을 수 있다.

console.log(person.key);
--> value

2. 괄호표기법

console.log(person["key"]);
-->value

괄호 안에는 문자열로 작성해야한다.

const name ="name";
console.log(person[name]);

만약 [ ]안에 문자열로 작성하고 싶지 않다면 다음 처럼 상수안에 문자열을 넣어주면 된다.

 

 

프로퍼티를 생성이후에 프로퍼티를 CRUD하는 방법

 

let person={
  name:"장도진",
  age:26
};

person.location="서울"
person["gender"]="남성"
//create
person.name="진도장"
person["age"]=25;
//update

delete person.age
delete person['name'];
person.name=null;
//delete
console.log(person);

삭제하는 방식중에서 delete를 사용하면 메모리 자체를 사용해서 배열을 바꾸게 될 뿐 메모리 자체가 지워지지는 않는다는 단점이 있다. 

그래서 그것 보다는 person.name=null 을 사용하여 객체에 null을 넣어버리는 방식을 사용하면 삭제와 같다.

 

메서드

let person={
  name:"장도진",//멤버
  age:26,//멤버
  say: function(){
    console.log("안녕 나는 ${this["name"]}") //여기서 this는 자기 자신을 가리키는 객체를 뜻한다.
  }//메서드
};
person.say();
person["say"]();

in 연산자 

console.log('name:${"name" in person}');  -->true

 

'개발 > javascript' 카테고리의 다른 글

[javascript] 응용1  (0) 2023.07.04
[javascript]기본정리5  (0) 2023.07.03
[javascript]기본정리3  (0) 2023.07.02
[javascript] 기본정리2  (0) 2023.07.01
[javascript] 기본 정리1  (0) 2023.07.01

함수 

function getArea(){
  let width=10;
  let height=20;

  let area=width*height;
  console.log(area);
}
//함수이름정의

getArea();
console.log("함수 실행 완료");

 

function getArea(width, height){
  let area=width*height;
  return area;
}

let area1=getArea(100,200);
console.log("area:",area1);
console.log("함수실행완료");

함수이름을 정의하고 ()안에 매개변수를 설정해주면 

함수 외부에서 대입을 통해 함수를 사용할 수 있다. 

예를 들어 다음과 같이 getArea를 설정하고 그 안에 매개변수인 width와 height를 설정하면 된다. 

 

지역변수와 전역변수 

함수 안에서 정의된 함수를 함수 밖에서 이용하려고 하면 Error가 발생하게 되는데 이와 같이 변수를 지역변수라고 칭한다. 

그러나 함수 밖에서 정의된 함수는 함수안이든 밖이든 상관 없이 사용 할 수 있는데 이러한 변수를 전역변수라고 한다.

 

함수도 값으로 취급하여 상수나 변수에 담아서 사용할 수 있다

let hello=function(){
  return "안녕하세요 여러분";
};                 //함수를 변수에 담아서 사용할 때는 굳이 함수의 이름을 정의할 필요가 없다.
                   //담긴 변수의 이름을 함수의 이름처럼 사용하면 된다.

console.log(hello);
const helloText=hello();
console.log(helloText);
--> 안녕하세요 여러분

이러한 것을 함수 표현식이라고 부른다 ( 변수에 담아서 활용하는 방식) 

 

function helloFunc(){
  return "안녕하세요 여러분";
}

이러한 방식을 함수 선언식이라고 한다.

 

위 두가지 방식의 차이점 

console.log(helloB())

let helloA=function(){
  return"안녕하세요 여러분";
};

function helloB(){
  return "안녕하세요 여러분";
}

다음과 같이 아래에서 선언된 helloB가 위에서 정상적으로 출력되고 있다.이러한 현상을 hoisting이라고 한다. 

 

hoisting : 함수선언식으로 만들어진 함수들은 실행전에 코드 최상단으로 끌어 올려지는 것을 말한다.

그러므로 함수선언식의 경우 밑바닥에 함수를 선언을 해도 정상적으로 잘 출력할 수 있다. 

 

함수 표현식은 함수선언식과는 다르게 Hoisting의 대상이 아니므로 해당함수가 직접적으로 선언되기 전에는 접근이 불가하다

 

화살표 함수 : 함수 표현식을 더 쉽게 사용하는 방법

let helloA =() =>{
	return "안녕하세요 여러분";
}


let helloA = ()=>"안녕하세요 여러분";
console.log(helloA());

이것 또한 hoisting의 대상이 아니므로 순서를 잘 지켜서 사용해야한다.

 

콜백함수 

함수의 매개변수로 함수를 넘겨준거??

function checkMood(mood, goodCallback,badCallback){
  if (mood==='good'){
    //기분 좋을 때 하는 동작
    goodCallback();
  } else{
    //기분 안 좋을 때 하는 동작 
    badCallback();
  }
}

function cry(){
  console.log("Action::Cry");
}
function sing(){
  console.log("Action::Sing");
}
function dance(){
  console.log("Action::Dance")
}

checkMood("good",sing,cry);

 

'개발 > javascript' 카테고리의 다른 글

[javascript] 응용1  (0) 2023.07.04
[javascript]기본정리5  (0) 2023.07.03
[javascript]기본정리4  (0) 2023.07.02
[javascript] 기본정리2  (0) 2023.07.01
[javascript] 기본 정리1  (0) 2023.07.01

연산자

산술연산자
let a =1; 
let b =2; 
console.log(a+b);-,*/,//,%등이 있음


연결 연산자 
let a="1";
let b="2";
console.log(a+b);
//12 그러나 묵시적 형변환이 일어 날 수도 있으니 항상 데이터 타입을 확인하는 습관을 가지고 있어야 한다 

복합연산자 
let a =5;
a+=10; // a=a+10
console.log(a);
//15

증감연산자 
숫자형에서만 사용할 수 있다
let a =10;
a++;
consol.log(a);
//11 
증감연산자를 뒤에 쓰면 console.log 이후 후반영이 되고 ++a처럼 앞에 쓰면 선반영된후 출력된다. 


논리연산자 
boolean자료형을 위한 연산자 
console.log(!true);
//false

console.log(true &&true) //true and true
//true
두개가 모두 참일 경우에만 참 
console.log(true && flase)
//false
console.log(false||false);// true or false


비교연산자 
let compareA= 1=="1";
console.log(compareA);
//true
==만 쓰면 값만 비교하게 됨 
자료형까지 비교하고 싶으면 ===으로 사용해야함 

let compareA= 1==="1";
console.log(compareA);
//false

let compareA = 1<=2;
console.log(compareA);
//false


typeof 연산자
let compareA=1;
compareA="1";
이렇게 해도 상관이 없음. 이건 동적타입언어이기 때문인데 이것은 유연하게 사용할 수 있다는 장점을 가지지만 
그만큼 에러가 발생할 확률이 높아짐 

그러므로
console.log(typeof compareA);
//string

null병합 연산자
let a;
a = a??10;
console.log(a);
//10

'개발 > javascript' 카테고리의 다른 글

[javascript] 응용1  (0) 2023.07.04
[javascript]기본정리5  (0) 2023.07.03
[javascript]기본정리4  (0) 2023.07.02
[javascript]기본정리3  (0) 2023.07.02
[javascript] 기본 정리1  (0) 2023.07.01

+ Recent posts