Promise가 뭔가요?
프로미스는 자바스크립트 비동기 처리에 사용되는 객체입니다. 여기서 자바스크립트의 비동기 처리란 ‘특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 자바스크립트의 특성’을 의미합니다.
https://joshua1988.github.io/web-development/javascript/promise-for-beginners/
ex)
function getData() {
var tableData;
$.get('https://domain.com/products/1', function(response) {
tableData = response;
});
return tableData;
}
console.log(getData()); // undefined=>
비동기 undefined 출력
ex) $.get()의 response 값이 tableData에 전달됨
function getData(callbackFunc) {
$.get('https://domain.com/products/1', function(response) {
callbackFunc(response); // 서버에서 받은 데이터 response를 callbackFunc() 함수에 넘겨줌
});
}
getData(function(tableData) {
console.log(tableData); // $.get()의 response 값이 tableData에 전달됨
});
async & await는 뭔가요?
async와 await는 자바스크립트의 비동기 처리 패턴 중 가장 최근에 나온 문법입니다. 기존의 비동기 처리 방식인 콜백 함수와 프로미스의 단점을 보완하고 개발자가 읽기 좋은 코드를 작성할 수 있게 도와주죠.
vue.js 에서 json 테스트 서버 설치 후 db.json 에 데이터 저장된다.
ID 는 자동 생성 된다.
async addTask(task){
//this.Tasks.push(task);
//this.Tasks = [...this.Tasks, task];
//데이터 저장 된다.
try {
const res =await fetch('api/tasks',{
method:"POST",
headers:{
'Content-type':"application/json",
},
body:JSON.stringify(task)
})
const data=await res.json();
this.Tasks=[...this.Tasks, data];
} catch (error) {
console.log(error);
}
}
json 서버 설치
1.
$ npm i json-server
2.
package.json 에 다음 추가
"backend":"json-server --watch db.json --port 5001"
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"backend":"json-server --watch db.json --port 5001"
},
3. db.json 파일 생성후 json 데이터 넣기
"backend":"json-server --watch db.json --port 5001"
https://github.com/bradtraversy/vue-crash-2021/blob/master/db.json
4. 실행
$ npm run backend
5. 확인 테스트
http://localhost:5001/tasks
예외 처리
동기/비동기 구분없이 try/catch로 일관되게 예외 처리를 할 수 있는 부분도 async/await를 사용해서 코딩했을 때의 큰 이점 중 하나입니다.
async function fetchAuthorName(postId) {
const postResponse = await fetch(
`https://jsonplaceholder.typicode.com/posts/${postId}`
);
const post = await postResponse.json();
const userId = post.userId;
try {
const userResponse = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`
);
const user = await userResponse.json();
return user.name;
} catch (err) {
console.log("Faile to fetch user:", err);
return "Unknown";
}
}
fetchAuthorName(1).then((name) => console.log("name:", name));
https://www.daleseo.com/js-async-async-await/












댓글 ( 4)
댓글 남기기