또 다른 비동기를 다루는 방식
async function 함수이름(){}
또는
const 함수이름 = async () => {}
// index.js
function sleep(ms){
return new Promise(resolve => setTimeout(resolve,ms));
}
// async/await
async function process(){
console.log('안녕하세요!');
await sleep(1000);
console.log('반갑습니다.');
return true;
}
process().then(value => {
console.log(value);
});
// 안녕하세요
// 반갑습니다
// true
// error catch
async function makeError(){
await sleep(1000);
const error = new Error();
throw error;
}
async function process(){
try {
await makeError();
} catch(e) {
console.log(e);
}
}
process();
// 1초 뒤에 Error 발생
// 바로 실행
(async function process(){
try {
await makeError();
} catch(e) {
console.log(e);
} finally {
console.log('end');
}
})();
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
// reject(new Error('reason');
}, ms);
});
}
async function asyncP(){
const ms = await p(1000);
return "Mark: " + ms;
}
(async function main(){
try{
const name = await asyncP();
console.log(name);
} catch(error){
console.log(error);
})();
// resolve → Mark : 1000ms
// reject → Error
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
// reject(new Error('reason');
}, ms);
});
}
// Promise
p(1000).then(()=>p(1000))
.then(()=>p(1000))
.then(()=>{
console.log('3000ms 후 실행');
});
// async await
(async function main(){
await p(1000);
await p(1000);
await p(1000);
console.log('3000ms 후 실행');
})();
function p(ms){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(ms);
// reject(new Error('reason');
}, ms);
});
}
// Promise.all
(async function main(){
const results = await Promise.all([p(1000),p(2000),p(3000)]);
console.log(results);
})(); // [1000,2000,3000]
// Promise.race
(async function main(){
const result = await Promise.race([p(1000),p(2000),p(3000)]);
console.log(result);
})(); // 1000