특정 작업을 시작하나서
완벽하게 다 처리하기 전에 실행 흐름이 바로 다음 코드로 넘어가고
나중에 콜백이 실행되는 것을 '비동기 실행'이라고 한다.
callback
나중에 어떤 조건이 만족된 후에 실행되는 함수
console.log('Start!');
fetch('https://www.google.com')
.then((response) => response.text())
.then((result) => { console.log(result); });
console.log('End');
코드 실행 순서
console.log('a');
setTimeout(() => { console.log('b'); }, 2000);
console.log('c');
파라미터1 : 콜백, { console.log('b'); }
파라미터2 : 실행 조건, 2000 밀리세컨즈 (=2초) 경과
수행 작업 : n 밀리세컨즈 후 콜백을 1번 실행
console.log('a');
setInterval(() => { console.log('b'); }, 2000);
console.log('c');
파라미터1 : 실행 조건 ( 특정 이벤트 ), click
파라미터2 : 콜백
수행 작업 : 특정 이벤트가 발생할 때마다 콜백을 실행
json = JSON.stringify(["apple", "banana"]);
console.log(`type : ${typeof json}`); // type : string
console.log(json); // ["apple", "banana"]
const rabbit = {
name: "tori",
birthDate: new Date(),
jump: () => {
console.log(`${name} can jump!`);
},
};
json = JSON.stringify(rabbit);
console.log(`type : ${typeof json}`); // type : string
console.log(json); // {"name":"tori","birthDate":"2022-03-18T08:56:58.879Z"}
객체의 메소드(함수)는 JSON.stringify() 포함되지 않는다.
json = JSON.stringify(rabbit, ["name"]);
console.log(json); // ["name":"tori"]
const rabbit = {
name: "tori",
birthDate: new Date(),
jump: () => {
console.log(`${name} can jump!`);
},
};
// 객체를 JSON 포맷의 문자열로 변환한다.
const json = JSON.stringify(rabbit);
// JSON 포맷의 문자열을 객체로 변환한다.
const obj = JSON.parse(json);
console.log(`type : ${typeof obj}`); // type : object
console.log(obj); // {name: 'tori', birthDate: '2022-03-19T04:46:30.600Z'}
rabbit 객체는 JSON.stringify()로 문자열 변환되어 Date() API를 사용할 수 없게된다.
console.log(`type : ${typeof rabbit.birthDate}`); // type : object
console.log(rabbit.birthDate.getFullYear()); // 2022
console.log(`type : ${typeof obj.birthDate}`); // string
console.log(obj.birthDate.getFullYear()); // Error
작업에 관한 3가지 상태 정보 및 해당 상태에 따른 결과값 (response) 을 갖고 있는 객체
pending ------ 진행 중
fulfilled ------ 성공
rejected ------ 실패
작업의 결과가 fulfilled면 작업 성공 결과
작업의 결과가 rejected면 작업 실패 이유
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.text())
.then(result => {
const users = JSON.parse(result);
return users[0];
})
.then(user => {
console.log(user);
const { address } = user;
return address;
})
.then(address => {
console.log(address);
const { geo } = address;
return geo;
})
fetch 함수에서 url로 리퀘스트를 보내고 promise 객체 리턴 (pending 상태)
순차적으로 콜백을 등록하고 promise 객체 리턴 → promise 객체의 총 갯수 : 5개 (pending)
fetch 함수 다음의 코드를 실행하다가
fetch 함수의 response 가 도착하면 fetch 함수의 promise 객체 의 상태가 pending에서 fullfiled 또는 rejected로 바뀌고, 상태 정보 및 상태에 따른 결과값 (response) 을 갖게 된다.
이 promise 객체가 다음 then 메소드 콜백의 파라미터로 넘어감.
then 메소드의 콜백이 실행되는데
1) then 메소드의 콜백이 또 promise 객체를 리턴하는 경우
then 메소드의 promise 객체 의 상태 (fulfilled or rejected)가
콜백의 promise의 상태 를 따라가고, 상태 정보 및 상태에 따른 결과값 (response) 을 갖게 된다.
이 promise 객체가 다음 then 메소드 콜백의 파라미터로 넘어감
2) then 메소드의 콜백이 promise 가 아닌 값을 리턴하는 경우
then 메소드의 promise 객체의 상태 가 fulfilled가 되고
상태 정보 및 상태에 따른 결과값 (response) 을 갖게 된다.
이 promise 객체가 다음 then 메소드 콜백의 파라미터로 넘어감.