[Vue 02] JS의 비동기처리
예
예준천
- Vue
const loadYear = async function(){
// xhr settings....
xhr.onload = function() {
// data 가공...
// list순회하며 <select> 태그에 각각 <option> appendChild...
}
await xhr.send();
}
$(document).ready(async function () {
const selectElementId = document.getElementById('');
await loadYear();
selectElementId.value = param;
});async function asyncFunction() {
return '결과값';
// 이는 Promise.resolve('결과값')과 동일하게 작동합니다.
}async function asyncFunction() {
let value = await someAsyncOperation();
// someAsyncOperation이 Promise를 반환하며, 그 해결을 기다립니다.
console.log(value); // Promise가 이행된 후에 실행됩니다.
}async function asyncFunction() {
try {
let value = await someAsyncOperation();
console.log(value);
} catch (error) {
console.error('에러 발생:', error);
}
}const loadYear = function() {
return new Promise((resolve) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data', true);
xhr.onload = function() {
// data 가공...
// list순회하며 <select> 태그에 각각 <option> appendChild...
resolve();
};
xhr.send();
});
};
loadYear().then(()=>{
// option들이 모두 추가된 뒤 해야하는 행동들
selectElementId.value = param;
})const useXhr = (method, url) =>
new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = () => {
reject(new Error("Network Error"));
};
});
// 사용
useXhr('GET', url)
.then(data => JSON.parse(data))
.then(res => 후처리)
.catch(err => console.log(err));
const loadYear = async function(){
// xhr settings....
xhr.onload = function() {
// data 가공...
// list순회하며 <select> 태그에 각각 <option> appendChild...
}
await xhr.send();
}
$(document).ready(async function () {
const selectElementId = document.getElementById('');
await loadYear();
console.log(selectElementId);
selectElementId.value = param;
});console.log(obj); // obj의 최신상태!!
console.log(JSON.parse(JSON.stringify(obj))); // 호출시점의 obj
console.log({...obj}); // 호출시점의 objconst loadYear = async function(){
// xhr settings....
xhr.onload = function() {
// data 가공...
// list순회하며 <select> 태그에 각각 <option> appendChild...
}
await xhr.send();
}
$(document).ready(async function () {
const selectElementId = document.getElementById('');
await loadYear();
setTimeout(()=>{selectElementId.value = param}, 1000);
});