📌102. promise와 async await 차이
const myPromise = () => Promise.resolve('I have resolved!');
function firstFunction() {
myPromise().then(res => console.log(res));
console.log('second');
}
async function secondFunction() {
console.log(await myPromise());
console.log('second');
}
firstFunction();
// second
// I have resolved!
secondFunction();
// I have resolved!
// second
- firstFunction에서 promise는 call stack이 비었을 때 실행된다
- 따라서 'second' 가 먼저 출력되고나서 promise가 resolve되고 'I have resolved!'가 출력된다
- 'second'를 promise 이후에 출력하고 싶으면 then chain으로 연결하면 된다
📌104. Promise.resolve()
Promise.resolve(5); // Promise {<fulfilled>: 5}
Promise.resolve() 메서드
- <fullfilled> 타입의 resolved value를 가진 Promise를 반환 (아직은 Promise)
- 값을 꺼내려면 .then() 사용해야 한다
📌108. 배열 고차함수 정리
// 아래 메서드들 중에 실제로 배열을 수정하는 것은?
const emojis = ['✨', '🥑', '😍'];
emojis.map(x => x + '✨');
emojis.filter(x => x !== '🥑');
emojis.find(x => x !== '🥑');
emojis.reduce((acc, cur) => acc + '✨');
emojis.slice(1, 2, '✨');
emojis.splice(1, 2, '✨');
// ✅ splice
- 새로운 배열을 반환: map, filter, slice
- 특정 조건을 만족하는 원소 반환: find
- 특정 값 반환: reduce
111. TDZ
let name = 'Lydia';
function getName() {
console.log(name);
let name = 'Sarah'; // 이 라인이 없으면 "Lydia" 정상 출력됨
}
getName(); // ReferenceError
let, const
- var와 마찬가지로 호이스팅되지만
- var와 다르게 값이 초기화되지는 않는다
- 따라서 선언 전에 참조하려고 하면 ReferenceError가 발생하고 이 구간을 TDZ라고 부른다
112. 제네레이터 함수와 yield*
function* generatorOne() {
yield ['a', 'b', 'c'];
}
function* generatorTwo() {
yield* ['a', 'b', 'c'];
}
const one = generatorOne();
const two = generatorTwo();
console.log(one.next().value); // ['a', 'b', 'c']
console.log(two.next().value); // a
- yield* 키워드를 사용하면 이터레이터의 원소들을 yield 할 수 있다
📌114. 호출되지 않은 setInterval()
let config = {
alert: setInterval(() => {
console.log('Alert!');
}, 1000),
};
config = null; // 이 라인이 없어도 setInterval 동작
// setInterval 이 동작
- setInterval() 은 즉시실행되고, timer id를 반환한다
- 따라서 실제로 config.alert 프로퍼티에는 setInterval 이 실행된 후 timer id 가 등록된다
📌122. typeof 반환값
const name = 'Lydia Hallie';
console.log(!typeof name === 'object'); // false
console.log(!typeof name === 'string'); // false
- typeof 반환값은 항상 문자열
- 예 "string", "object"
124. isNaN
const name = 'Lydia Hallie';
const age = 21;
console.log(Number.isNaN(name)); // false
console.log(Number.isNaN(age)); // false
console.log(isNaN(name)); // true
console.log(isNaN(age)); // false
Number.isNaN 메서드와 isNaN 메서드는 다르다
- isNaN 메서드는 숫자가 아닌 값을 받으면 true를 반환해버린다
참고