JavaScript
Async 와 await
유병각
2022. 2. 4. 01:14
async 와 await 의 개념
서버로 비동기 요청을 보낼 때 코드가 예상과는 다르게 작동할 때가 있다.
import axios from "axios";
function getRequest() {
return axios({
method: "get",
url: "https://jsonplaceholder.typicode.com/todos/1",
});
}
function getInfo() {
const data = getRequest().then((res) => res.data);
console.log(data); // Promise { <pending> }
}
getInfo();
위의 코드에서 서버로 요청을 보내 값을 data 라는 변수에 저장한 뒤,
해당 값을 사용하려고 한다.
하지만, 위의 경우에 콘솔에 찍히는 data 는 서버에서 받아온 데이터가 아닌, promise<pending> 이다.
그 이유는 서버에서 정보를 받아오기도 전에 console.log(data) 라는 자바스크립트 코드가 먼저 실행되기 때문이다.
이렇게 비동기로 인해 발생하는 문제를 해결하기 위해서 async 와 await 를 사용할 수 있다.
import axios from "axios";
function getRequest() {
return axios({
method: "get",
url: "https://jsonplaceholder.typicode.com/todos/1",
});
}
async function getInfo() {
const data = await getRequest().then((res) => res.data);
console.log(data); // { userId: 1, id: 1, title: 'delectus aut autem', completed: false }
}
getInfo();
이와같이 async 와 await 를 사용하면 내가 원하는대로 코드가 작동하는걸 알 수 있다.
즉, 코드의 흐름이 정상적으로 위에서 아래로 진행되어 가독성을 높일 수 있다.
또한 try , catch 를 병행해서 사용하면 깔끔하게 작동하는 코드를 만들 수 있다.
import axios from "axios";
function getRequest() {
return axios({
method: "get",
url: "https://jsonplaceholder.typicode.com/todoqqs/1",
});
}
const getInfo = async () => {
try {
const data = await getRequest().then((res) => res.data);
console.log("getInfo");
console.log(data);
} catch (err) {
console.log("error");
}
};
getInfo();