Skip to content

Instantly share code, notes, and snippets.

@yeonwooz
Created March 14, 2022 06:34
Show Gist options
  • Save yeonwooz/b526a1a7a4fbcb74039eca26c29333f0 to your computer and use it in GitHub Desktop.
Save yeonwooz/b526a1a7a4fbcb74039eca26c29333f0 to your computer and use it in GitHub Desktop.
즉시실행함수를 이용한 병렬처리
const fac = (n) => {
if (n === 1) {
return 1
}
return fac(n-1) * n
}
function bar(n) {
console.time('b')
return new Promise((resolve) => {
setTimeout(()=>{
resolve(fac(n))
console.timeEnd('b') // 2000ms
}, 2000) // 2초 걸리는 팩토리얼 호출 함수
})
}
// async 키워드로 선언하면 리턴값이 Promise 가 아니어도 자동으로 Promise가 리턴됨
// 명시적으로 Promise 객체를 리턴한다면 async 키워드 있으나 없으나 똑같음
function car(n) {
console.time('c')
const resPromise = bar(n)
return new Promise((resolve)=>{
setTimeout(()=>{
resolve(resPromise)
console.timeEnd('c') // 3000ms
}, 3000)
})
}
(async ()=>{
console.time('a')
const response = await car(5)
console.log(response)
console.timeEnd('a') // 3000ms
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment