JavaScript_비동기통신
26 Jul 2023테킷 멋쟁이사자처럼 JavaScript
Promise
- new Promise로 promise 객체 반환
- 매개변수 (resolve, reject) 처리
- resolve => then
-
reject => catch
- Ajax 진행 순서
- open
- setRequestHeader
- readystatechange
- send
xhr
const defaultOptions = {
method: "GET",
url: "",
body: null,
errorMessage: "서버와의 통신이 원할하지 않습니다.",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
};
/* promise API */
export function xhrPromise(options) {
const { method, url, body, errorMessage, headers } = {
...defaultOptions,
...options,
};
// const config = Object.assign({}, defaultOptions, options);
if (!url) throw new Error("서버와 통신할 url은 필수값입니다.");
if (!url) refError("서버와 통신할 url은 필수값입니다.");
const xhr = new XMLHttpRequest();
xhr.open(method, url);
Object.entries(headers).forEach(([key, value]) => {
xhr.setRequestHeader(key, value);
});
xhr.send(JSON.stringify(body));
return new Promise((resolve, reject) => {
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 400) {
resolve(JSON.parse(xhr.response));
} else {
reject({ message: errorMessage });
}
}
});
});
}
xhrPromise.get = (url) => {
return xhrPromise({
url,
});
};
xhrPromise.post = (url, body) => {
return xhrPromise({
url,
body,
method: "POST",
});
};
xhrPromise.delete = (url) => {
return xhrPromise({
url,
method: "DELETE",
});
};
xhrPromise.put = (url, body) => {
return xhrPromise({
url,
body,
method: "PUT",
});
};
async
async function 라면끓이기() {
delayP({ data: "물 넣기" }).then((res) => {
console.log(res);
});
const 스프 = await delayP({ data: "스프 넣기" });
console.log(스프);
const 면 = await delayP({ data: "면넣기" });
console.log(면);
const 계란 = await delayP({ data: "계란넣기" });
console.log(계란);
const 접시 = await delayP({ data: "접시" });
console.log(접시);
}
fetch
const URL = "https://jsonplaceholder.typicode.com/users";
const defaultOptions = {
method: "GET",
body: null,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
};
export const tiger = async (options) => {
const { url, ...restOptions } = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers,
},
};
const response = await fetch(url, restOptions);
if (response.ok) {
response.data = await response.json();
}
return response;
};
tiger.get = (url, options) => {
return tiger({
url,
...options,
});
};
tiger.post = (url, body, options) => {
return tiger({
method: "POST",
url,
body: JSON.stringify(body),
...options,
});
};
tiger.put = (url, body, options) => {
return tiger({
method: "PUT",
url,
body: JSON.stringify(body),
...options,
});
};
tiger.delete = (url, options) => {
return tiger({
method: "DELETE",
url,
...options,
});
};