timer(1000,function(){
console.log('작업');
timer(1000,function(){
console.log('작업');
});
});
비동기 작업시
타이머 작업 후 또 타이머 작업을 해야한다면..
콜백안에 반복해서 콜백이 들어가는 .. 콜백 지옥 발생
--> 이 때문에 promise
가 등장!
timer(1000)
.then(function(){
console.log('작업')
return timer(1000);
})
.then(function(){
console.log('작업')
return timer(1000);
})
여기서 만족하지 않고 발전한 것이.. async&awiat
동기적 코드처럼 작성하는 문법적 단순화
await
붙이기await
이 붙은 프로미스를 리턴하는 함수는 반드시 다른 어떤 함수 안에 들어가있어야 하고, 그 함수는 async
라는 키워드가 붙어있어야 함async funtion run(){
await timer(1000)
console.log('작업')
await timer(1000)
console.log('작업')
}
run();
console.log('start');
timer(1000).then(function(time){
console.log('time:'+time);
return timer(time+1000);
}).then(function(time){
console.log('time:'+time);
return timer(time+1000);
}).then(function(time){
console.log('time:'+time);
console.log('end') // 함수안에 적지 않으면 timer보다 먼저 end가 나옴
});
출력
start
time:1000
time:2000
time:3000
end
async function run() {
console.log('start');
var time = await timer(1000); //timer가 비동기적이라는 것을 명확하게 함
console.log('time:'+time);
time = await timer(time+1000);
console.log('time:'+time);
time = await timer(time+1000);
console.log('time:'+time);
console.log('end')
}
async function run2(){
console.log('parent start');
var time = await run();
console.log('parent end');
}
run();
await
를 쓰면 timer(1000)
의 리턴값을 time
으로 받는데, 이는 .then(function(time){})의 time과 같은 것임async
가 붙은 run()
이라는 함수는 비동기적인 함수: promise
를 리턴함await
를 또 붙일수 있다는 의미async
는 평범한 함수를 프로미스를 리턴하는 비동기적으로 만들어주는 키워드이고, 그렇가 때문에 그 안에서 await
를 사용할 수 있는 것