async function f(){
return 1;
}
f().then(console.log)
class Waiter {
async wait(){
return await Promise.resolve(1);
}
}
new Waiter()
.wait()
.then('>>',console.log)
async function f(){
let promise = new Promise(((resolve, reject) => {
setTimeout(()=> resolve("완료"),1000);
}));
let result = await promise;
console.log(result);
}
f();
async function f() {
try {
let response = await fetch('http://유효하지-않은-url');
let user = await response.json();
} catch(err) {
// fetch와 response.json에서 발행한 에러 모두를 여기서 잡습니다.
console.log(err);
}
}
f();
⇒ async/await
를 함께 사용하면 읽고, 쓰기 쉬운 비동기 코드를 작성할 수 있음
⇒ async/await
사용하면 .then/catch 거의 사용 X
async/await
가 프라미스 기반으로 한다는 사실 인지async function loadJson(url){
let response = await fetch(url);
if(response.status == 200){
return response.json();
}
throw new Error(response.status);
}
//loadJson 호출하는 코드는 async함수 내부가 아니므로 await 불가
loadJson('no-such-user.json')
.catch(console.log)
async function wait() {
await new Promise(resolve => setTimeout(resolve, 1000));
return 10;
}
function f() {
// ...코드...
// async wait()를 호출하고 그 결과인 10을 얻을 때까지 기다리려면 어떻게 해야 할까요?
// f는 일반 함수이기 때문에 여기선 'await'를 사용할 수 없다는 점에 주의하세요!
wait().then(result => console.log(result));
}
f();