Promise & Promise.all()
const onClickPromise = async () => {
const result1 = await new Promise((resolve, reject) => {
setTimeout((resolve("3초 후 실행됩니다.")) => {}, 3000)
})
const result2 = await new Promise((resolve, reject) => {
setTimeout((resolve("2초 후 실행됩니다.")) => {}, 2000)
})
const result3 = await new Promise((resolve, reject) => {
setTimeout((resolve("1초 후 실행됩니다.")) => {}, 1000)
})
};
const onClickPromiseAll = async () => {
const result = await Promise.all([
setTimeout((resolve("3초 후 실행됩니다.")) => {}, 3000)
setTimeout((resolve("2초 후 실행됩니다.")) => {}, 2000)
setTimeout((resolve("1초 후 실행됩니다.")) => {}, 1000)
])
};
Promise
- 위의 함수는 result1 이 실행되고 난 후에 result2가 실행이 되고, result2가 실행된 후에, result3이 실행된다.
- 따라서 onClickPromise 함수의 경우 약 6초의 시간이 소요된다.
Promise.all()
- Promise.all() 의 경우에는 Promise.all()에 포함되어 있는 함수들을 동시에 실행한다.
- 따라서 onClickPromiseAll 함수의 경우 약 3초의 시간이 소요된다.
Promise.all() - map
- Promise.all()을 사용하여 한번에 여러 함수를 실행할 때에는 map, for, forEach를 사용할 수 있다.
const onClickPromiseAll = async () => {
const result = await Promise.all(["http://storage.url1.jpg",
"http://storage.url1.jpg", "http://storage.url1.jpg"].map((el)
=> new Promise((resolve, reject) => {
setTimeout(() => {
resolve(el)
}, 3000)
})
))
};