순차적으로 처리해야할 콜백이 여러개 일경우 처리방법
function gotoCode() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('1. go to code') }, 100)
})
}
function sitAndCode() {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('2. sit and code') }, 100)
})
}
gotoCodestates()
.then(data => {
console.log(data)
sitAndCode()
.then(data => {
console.log(data)
...()
}
}
gotoCodestates()
.then(data => {
console.log(data)
return sitAndCode()
})
.then(data => {
console.log(data)
return ...()
})
console.time("소요시간");
await display("jacob", 3000);
await display("제이콥", 2000);
await display("콥짱", 1000);
console.timeEnd("소유시간");
// 소요시간 : 약 6000ms
2 promise.all을 사용한경우
console.time("소요시간");
await.Promise.all([
display("jacob", 3000);
display("제이콥", 2000);
display("콥짱", 1000);
]);
console.timeEnd("소유시간");
// 소유시간: 약 3000ms
promise.all을 사용할 경우 훨씬 단축된 시간을 확인할 수 있다.
1번을 경우 함수 하나하나 다 기다렸다가 실행값을 return 한다.
2번 Promise.all의 경우 병렬로 비동기 함수를 실행시켰기 때문에 빠르게 진행된다.
Promise.all 순서대로 실행하지만 비동기적으로 함수 실행되므로 반환 순서는 달라질수 있다.
출처: https://code-masterjung.tistory.com/91
에러가 발생할경우 다른 프로미스의 결과는 무시된다. 주의 ~!