*Udemy의 The Complete JavaScript Course 2020: Build Real Projects! 참고
const getIDs = new Promise((resolve, reject) => {
setTimeout(() => {
resolve([523, 883, 432, 974]);
}, 1500);
});
const getRecipe = (recID) => {
return new Promise((resolve, reject) => {
setTimeout(
(ID) => {
const recipe = { title: "Fresh tomato pasta", publisher: "Jonas" };
resolve(`${ID}: ${recipe.title}`);
},
1500,
recID
);
});
};
const getRelated = (publisher) => {
return new Promise((resolve, reject) => {
setTimeout(
(pub) => {
const recipe = { title: "Italian Pizza", publisher: "Jonas" };
resolve(`${pub}: ${recipe.title}`);
},
1500,
publisher
);
});
};
getIDs
.then((IDs) => {
console.log(IDs);
return getRecipe(IDs[2]);
})
.then((recipe) => {
console.log(recipe);
return getRelated("Jonas Schmedtmann");
})
.then((recipe) => {
console.log(recipe);
})
.catch((error) => {
console.log("Error!!");
});
Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.
Promise는 다음 중 하나의 상태를 가집니다.
대기(pending): 이행하거나 거부되지 않은 초기 상태.
이행(fulfilled): 연산이 성공적으로 완료됨.
거부(rejected): 연산이 실패함.
참고-https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise
async function getRecipesAW() {
const IDs = await getIDs;
console.log(IDs);
const recipe = await getRecipe(IDs[2]);
console.log(recipe);
const related = await getRelated("Jonas Schmedtmann");
console.log(related);
return recipe;
}
getRecipesAW().then((result) => console.log(`${result} is the best ever!`));
async function 선언은 AsyncFunction객체를 반환하는 하나의 비동기 함수를 정의합니다.
비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로,
암시적으로 Promise를 사용하여 결과를 반환합니다.
참고-https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/async_function
function getWeather(woeid) {
fetch(`https://crossorigin.me/https://www.metaweather.com/api/location/${woeid}/`)
.then(result => {
// console.log(result);
return result.json();
})
.then(data => {
// console.log(data);
const today = data.consolidated_weather[0];
console.log(`Temperatures today in ${data.title} stay between ${today.min_temp} and ${today.max_temp}.`);
})
.catch(error => console.log(error));
}
getWeather(2487956);
getWeather(44418);
async function getWeatherAW(woeid) {
try {
const result = await fetch(
`https://crossorigin.me/https://www.metaweather.com/api/location/${woeid}/`
);
const data = await result.json();
const tomorrow = data.consolidated_weather[1];
console.log(
`Temperatures tomorrow in ${data.title} stay between ${tomorrow.min_temp} and ${tomorrow.max_temp}.`
);
return data;
} catch (error) {
alert(error);
}
}
getWeatherAW(2487956);
fetch
참고-https://developer.mozilla.org/ko/docs/Web/API/Fetch_API
budgety app 1편 (0) | 2020.09.15 |
---|---|
자바스크립트 중간중간 모르는 것들! (0) | 2020.08.07 |
자바스크립트 비동기 프로그래밍 1편 (0) | 2020.08.07 |
자바스크립트 ES6 4편 (0) | 2020.08.07 |
자바스크립트 ES6 3편 (0) | 2020.08.07 |