npx json-server --watch dj.json
npx json-server --watch -p 3001 dj.json
json-server: json-server를 열겠다.
--watch: db.json파일 변경시 서버 재시동을 안해도 json-server에 바로 반영되게 하는 기능
db.json: 파일 이름
-p 3001: 3001포트로 서버를 열겠다.
콜백함수 안에 콜백함수 -> 복잡해지는걸 call back hell 이라고 한다.
async, await는 비동기적 코드를 동기적인 코드인거처럼 바꾼다. -> callback 함수를 감춘다.
response = await fetch('http://localhost:3000/topics')
fetch의 return값: promise
-> 앞에 await 붙인다 -> 처음 then의 인수값을 return 한다. (res)
await는 반드시 async 함수 안에서 실행된다.
async function() {} -> 이 함수의 리턴값: promise
// const topics = [
// {id:1, title:'html', body:'html is ...'},
// {id:2, title:'css', body:'css is ...'},
// {id:3, title:'js', body:'js is ...'}
// ];
let nextId = 4;
let selectedId = null;
function navHandler(e){
// 1. 링크가 작동하지 않아야 한다.
e.preventDefault();
// 2. 아이디 값을 알아낸다.
selectedId = Number(e.target.id);
read();
}
async function nav(){
document.querySelector('nav>ol').innerHTML = 'Loading....'
let response = await fetch('http://localhost:3000/topics');
let topics = await response.json();
const tag = topics.map(e=>`
<li>
<a href="/read/${e.id}" id="${e.id}">
${e.title}
</a>
</li>`).join('');
document.querySelector('nav>ol').innerHTML = tag;
}
function welcome(e){
document.querySelector('article').innerHTML = `<h2>Welcome</h2>Hello, WEB`;
selectedId = null;
control();
}
async function read(){
let response = await fetch('http://localhost:3000/topics/' + selectedId)
let topic = await response.json();
const content = `<h2>${topic.title}</h2>${topic.body}`;
document.querySelector('article').innerHTML = content;
control();
}
async function createHandler(e){
e.preventDefault();
const t = e.target.title.value;
const b = e.target.body.value;
let response = await fetch('http://localhost:3000/topics/', {
method:'POST',
headers: {
'Content-Type':'application/json'
},
body:JSON.stringify({title: t, body: b})
});
let data = await response.json();
nav();
selectedId = data.id;
read();
}
function create(){
const content = `
<form>
<p><input type="text" name="title" placeholder="제목"></p>
<p><textarea name="body" placeholder="본문"></textarea></p>
<p><input type="submit" value="create"></p>
</form>
`;
document.querySelector('article').innerHTML = content;
}
async function updateHandler(e){
e.preventDefault();
const t = e.target.title.value;
const b = e.target.body.value;
let response = await fetch('http://localhost:3000/topics/'+selectedId, {
method:'PUT',
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify({title:t, body:b})
});
let data = await response.json();
nav();
selectedId = data.id;
read();
}
async function update(){
// fetch('http://localhost:3000/topics/' + selectedId)
// .then(res => res.json())
// .then(topic => {
// const content = `
// <form>
// <p><input type="text" name="title" placeholder="제목" value="${topic.title}"></p>
// <p><textarea name="body" placeholder="본문">${topic.body}</textarea></p>
// <p><input type="submit" value="update"></p>
// </form>
// `;
// document.querySelector('article').innerHTML = content;
// control();
// })
let response = await fetch('http://localhost:3000/topics/' + selectedId);
let topic = await response.json();
const content = `
<form>
<p><input type="text" name="title" placeholder="제목" value="${topic.title}"></p>
<p><textarea name="body" placeholder="본문">${topic.body}</textarea></p>
<p><input type="submit" value="update"></p>
</form>
`;
document.querySelector('article').innerHTML = content;
control();
}
async function del(){
let response = await fetch('http://localhost:3000/topics/' + selectedId, {
method:'DELETE'
});
let data = await response.json();
nav();
selectedId = null;
welcome();
}
function control(){
let contextUI = ''
if(selectedId !== null){
contextUI = `
<li><a href="/update">Update</a></li>
<li><a href="/delete">Delete</a></li>
`;
}
document.querySelector('#control').innerHTML = `
<li><a href="/create">Create</a></li>
${contextUI}
`;
}
nav();
welcome();
비교
function nav(){
fetch('http://localhost:3000/topics')
.then(res => res.json())
.then(topics => {
const tag = topics.map(e=>`
<li>
<a href="/read/${e.id}" id="${e.id}">
${e.title}
</a>
</li>`).join('');
document.querySelector('nav>ol').innerHTML = tag;
})
document.querySelector('nav>ol').innerHTML = 'loading ...'
}
async function nav(){
document.querySelector('nav>ol').innerHTML = 'Loading....'
let response = await fetch('http://localhost:3000/topics');
let topics = await response.json();
const tag = topics.map(e=>`
<li>
<a href="/read/${e.id}" id="${e.id}">
${e.title}
</a>
</li>`).join('');
document.querySelector('nav>ol').innerHTML = tag;
}
let response = await fetch('http://localhost:3000/topics');
이건 fetch('http://localhost:3000/topics') .then(res
이 코드와 같다. 즉, response = res이다.async function updateHandler(e){
e.preventDefault();
const t = e.target.title.value;
const b = e.target.body.value;
let response = await fetch('http://localhost:3000/topics/'+selectedId, {
method:'PUT',
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify({title:t, body:b})
});
let data = await response.json();
nav();
selectedId = data.id;
read();
}
fetch안에 method, headers, body써주는건 똑같다.
fetch('http://localhost:3000/topics')
.then(function(response){
return response.json();
})
.then(function(topics){
console.log(topics[0]);
let firstId = topics[0].id;
console.log(firstId);
});
response = await fetch('http://localhost:3000/topics');
topics = await response.json();
newRes = await fetch(`http://localhost:3000/topics/` + topics[0].id);
newTopics = await newRes.json();
function timer(callback, time) {
setTimeout(function() {
callback(time);
}, time)
}
timer(function(time) {console.log('timeout', time)}, 2000)
타이머 안의 타이머
timer(function(time){
console.log('timeout1', time);
timer(function(time){
console.log('timeout2', time);
}, 2000);
}, 2000)
-> 실행 -> 2초 -> 타임아웃1 출력 -> 2초 -> 타임아웃2 출력
function timer(time){
return new Promise(function(resolve){
setTimeout(function(){
resolve(time);
}, time);
});
}
timer(1000)
.then(res => console.log(res))
// 위 아래 같은코드
time = await timer(1000);
console.log(time);
time = await timer(1000);
console.log(time);
time = await timer(1000+time);
console.log(time);
time = await timer(1000+time);
console.log(time);
비동기적으로 하려면 then을 써야함
console.time('race');
result = await Promise.race([timer(1000), timer(2000), timer(3000)]);
console.log(result);
console.timeEnd('race');
console.time('race');
result = await Promise.all([timer(1000), timer(2000), timer(3000)]);
console.log(result);
console.timeEnd('race');
async 함수의 return 값은 promise로 감싸진다.
그래서 함수호출할때 await붙여서 호출함.
async function test() {
// This function will print "Hello, World!" after 1 second.
await new Promise(resolve => setTimeout(() => resolve(), 1000));
console.log('Hello, World!');
}
test();
async function test() {
// Wait 100ms 10 times. This function also prints after 1 sec.
for (let i = 0; i < 10; ++i) {
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log('Hello, World!');
}
test();
async function test() {
while (true) {
// Convoluted way to print out "Hello, World!" once per
// second by pausing execution for 200ms 5 times
for (let i = 0; i < 10; ++i) {
if (i % 2 === 0) {
await new Promise(resolve => setTimeout(resolve, 200));
}
}
console.log('Hello, World!');
}
}