2021/02 54

async/ await 사용방법 (feat. then과 함께 쓰기)

async와 await은 세트로 다니는데, await은 Promise가 적용되는 함수 앞에 쓰입니다. 1. async/await 사용방법 function sleep(ms){ return new Promise(resolve => setTimeout(resolve, ms)); } async function process(){ console.log('안녕하세요'); await sleep(1000); console.log('반갑습니다!'); } process(); 이렇게 보면 굳이 Promise 뒤에 .then을 사용하지 않아도 되고 setTime을 하지않아도 await으로 설정할수있게 됩니다. 이것을 보면 다른 함수를 만들어서 선언하는것이 아니기 때문에 분기점 만드는것도 쉽습니다. 변수를 공유하는것도 쉬워져서..

Promise 나온이유 및 사용방법(feat. 만약 callback함수를 쓰게 된다면?, Promise의 문제점)

ES6 버전에서 나왔고 비동기작업을 쉽게 처리할 수 있도록 도와주는 역할을 합니다. 이전에는 비동기작업이 끝나면 실행하라고 callback함수를 이용했었습니다. callback함수로 처리하게 된다면 비동기 작업이 많아질 경우 코드가 매우 복잡해지게 되었습니다. 그래서 promise가 나왔습니다. 원래는 라이브러리로 존재했었습니다. 그런데, 이제는 매우 편하다 보니 아애 자바스크립트 스팩에 추가 되었습니다. 1. Promise 사용방법 (resolve, then) 성공했을때 const myPromise = new Promise((resolve, reject)=>{ setTimeout(()=>{ resolve('hello'); }, 1000) }); myPromise.then(result=>{ console..

Javascript 비동기 처리의 이해 (feat. 주로 처리하는 작업)

작업이 빨리 끝나는 순서대로 출력이 되는것입니다. 우선 예를 보여드리겠습니다. function work(){ setTimeout(()=>{ const start = Date.now(); for(let i =0; i 만약 서버쪽에서 데이터를 받아올때는 요청을 하고 서버에서 응답을 할때까지 대기를 해야하기 때문에 비동기 작업을 처리합니다. 2. 파일 읽기 --> 주로 서버쪽에서 어떤 파일을 읽어와야하는 경우에 비동기 작업을 처리합니다. 3. 암호화/복호화 --> 암호화, 복호화 하는 과정에도 시간이 걸리기 때문에 비동기 작업을 처리합니다. 4. 작업예약 --> 어떤 작업을 예약해야할때 set time out을 이용해서 비동기 작업을 처리합니다. 또한 callback, promise, async await이 ..

함수 파라미터에서의 rest와 함수 인자에서의spread(feat. reduce)

1. 함수 파라미터에서 rest function sum(...rest){ return rest.reduce((acc, current)=> acc+current,0); } console.log(sum(1,2,3,4,5,6,7,8)); //출력값 36 매개변수에 rest를 선언하면 그 자체가 배열로 인식이 됩니다. 즉, ...rest 매개변수는 = [1,2,3,4,5,6,7,8] 로 인식이 되고 있는겁니다. 2. 함수 인자에서의 spread function max(...numbers){ return numbers.reduce((acc,current)=>( acc>current ? acc:current ),numbers[0]); } const numbers = [1,2,3,4,10,5,6,7]; const r..

Javascript/함수 2021.02.02

spread 와 rest-spread 연산자 (feat. 비구조화할당)

1. spread 연산자 객체에서 이용하기 const slime = { name: '슬라임' }; const cuteSlime = { ...slime, attribute: 'cute' }; const purpleCuteSlime = { ...cuteSlime, color: 'purple' }; const greenCuteSlime = { ...purpleCuteSlime, color: 'green' }; console.log(slime); console.log(cuteSlime); console.log(purpleCuteSlime); console.log(greenCuteSlime); //출력값 { name: '슬라임' } { name: '슬라임', attribute: 'cute' } { name: '슬..

비구조화 할당(구조 분해)

해당 객체의 값을 알아내고싶을때 이용합니다. 구조 분해 할당의 구문은 기존 할당문과 비슷하지만, 대신 할당문의 좌변에서 사용하여, 원래 변수에서 어떤 값을 분해해 할당할지 정의합니다. 1. 값을 나눠서 구하는 방법 const deepObject = { state:{ information: { name: 'velopert', languages: ['korean', 'english', 'chinese'] } }, value: 5 }; const {name, languages} = deepObject.state.information; const {value} = deepObject; const extracted = { name, languages, value }; console.log(extracted); /..

Javascript/기초 2021.02.01

Javascript 조건문을 스마트하게 사용하는 방법 (include, 화살표함수, 객체활용)

특정값이 여러값중에 하나인지 아닌지 확인하는 방법 function isAnimal(text){ return( text == '고양이' || text == '개' || text == '너구리' || text == '거북이' ); } console.log(isAnimal('개')); console.log(isAnimal('노트북')); //출력값 true false 다음과 같이 return하게 되면 식이 매우 복잡하게 되는걸 보실 수 있습니다. 이것을 간단하게 해결하는 방법은 include입니다. 1. include 사용방법 우선 비교하고싶은 값들을 배열안에 넣습니다. function isAnimal(text) { const animals = ['고양이', '개', '너구리', '거북이']; return a..

Javascript 함수의 기본 파라미터 (기본값지정 방법)

파라미터값이 없을경우에 변수 혹은 함수안에 변수 계산은 어떻게 해야할까요? 기본값을 지정하는 방법이 있습니다. 1. 매개변수 기본값 지정 (함수일 경우) function calculatecircleArea(r=1){ return Math.PI *r *r; } const area = calculatecircleArea(); console.log(area); 2. 매개변수 기본값 지정 (함수가 아닐 경우) const calculatecircleArea = (r = 1) => Math.PI * r * r; const area = calculatecircleArea(); console.log(area);

Javascript/기초 2021.02.01

단축 평가 논리 계산법 (short-circuit evaluation) --> react에서 조건부 랜더링에 사용됨

&&로 값을 비교하기 const dog = { name: '멍멍이' }; function getName(animal){ return animal && animal.name; } const name = getName(dog); console.log(name); //출력값 멍멍이 여기서보면 궁금증이 생깁니다. 분명 형식은 Boolean으로 구분하는것같지만 출력값은 다르게 나오기 때문이죠. 이 특성을 알기 위해 다른 예시를 보겠습니다. console.log(true && 'hello'); console.log(false && 'hello'); console.log('hello' && 'bye' && 'nice'); //출력값 hello false nice &&특성을 보면 만약 비교값중에 무조건 falsy값이 ..

Truthy and Falsy (feat. null checking) --> falsy한 값을 잘 기억해야합니다.

true같은것과 false같은것을 말하는 겁니다. 이 개념을하기전에는 일단 null인지 아닌지 체크하는방법을 알려드리겠습니다. 1. undefined || null 로 확인 function print(person){ if(person === undefined || person === null){ return; } console.log(person.name); } const person = null; print(person); 이것은 코드를 이해하기 쉬운방법이지만, 함수에 들어갈때마다 이러한 조건문으로 확인하는것은 비효율적입니다. 2. 조건문에 !를 넣는 방법 function print(person){ if(!person){ return; } console.log(person.name); } const p..

Javascript/기초 2021.02.01