μ‹œνλ¦¬ν‹°μ§€ν˜Έ 2023. 12. 1. 08:21

Syncronous & Asychronous

 

1. 일반적인 λ§₯λ½μ—μ„œμ˜ 동기(Sync)

μ˜μƒμ„ 보닀가 μžλ§‰μ΄ μ˜μƒλ³΄λ‹€ λΉ λ₯΄κ±°λ‚˜ 늦게 좜λ ₯λ˜λŠ” 경우, '싱크(Sync)κ°€ μ•ˆ λ§žλŠ”λ‹€' λΌλŠ” 말을 μ‚¬μš©ν•œλ‹€. μ΄λŠ” 비동기(Asychronous)λ₯Ό μ˜λ―Έν•œλ‹€.

 

μ΄λ•Œμ˜ μ‹±ν¬λŠ” Syncλ₯Ό μ˜λ―Έν•˜λŠ”λ°, sysnchronous의 μ€„μž„λ§λ‘œμ„œ, '동기'ν˜Ήμ€ 'λ™μ‹œμ— μΌμ–΄λ‚˜λŠ”, ν•œ κ°€μ§€ 동, 기닀릴 κΈ°)' μ΄λΌλŠ” 의미λ₯Ό κ°€μ§€κ³  μžˆλ‹€.

 

2. ν”„λ‘œκ·Έλž˜λ°μ—μ„œμ˜ 동기(Sync)와 비동기(Async)

동기, Synchronous

 

이전 μž‘μ—…μ΄ λ‹€ μˆ˜ν–‰λ˜μ§€ μ•Šμ„ 경우, λ‹€μŒ μž‘μ—…μ€ μˆ˜ν–‰λ˜μ§€ μ•Šμ„ 경우, λ‹€μŒ μž‘μ—…μ€ μˆ˜ν–‰ν•˜μ§€ λͺ»ν•˜λŠ” μƒνƒœκ°€ λœλ‹€.

이λ₯Ό (Blocking) 이라고 ν•œλ‹€.

 

ex) 둜그인 λ²„νŠΌ 클릭 μ‹œ 화면이 μƒˆλ‘œκ³ μΉ¨ λ˜λ©΄μ„œ 둜그인 ν™”λ©΄μœΌλ‘œ μ „ν™˜ λ˜μ–΄μ•Ό ν•  λ•Œ 둜그인 ν™”λ©΄μœΌλ‘œ μ΄λ™ν•˜λŠ” λ™μ•ˆ μ‚¬μš©μžλŠ” ν•΄λ‹Ή 화면이 λ‚˜μ˜¬ λ•Œ κΉŒμ§€ λ‹€λ₯Έ λ™μž‘μ„ ν•  수 μ—†κ²Œ λœλ‹€.

 

비동기, Asynchronous

 

이전 μž‘μ—…μ˜ μˆ˜ν–‰ 여뢀에 상관없이 λ‹€μŒ μž‘μ—…μ€ κ°œλ³„λ‘œ μˆ˜ν–‰(Non-Blocking)

 

비동기 방식은 처리 μˆœμ„œκ°€ 보μž₯λ˜μ§€ μ•ŠλŠ” λŒ€μ‹  동기 방식에 λΉ„ν•΄ κ²°κ³Ό ν•˜λ©΄μ΄ λ‚˜μ˜€λŠ” μ‹œκ°„ λ™μ•ˆ λ‹€λ₯Έ μž‘μ—…μ„ ν•  수 μžˆλ‹€λŠ” μž₯점이 μžˆλ‹€.

 

 

 

 

// μ½”λ“œλ‘œ λ³΄λŠ” 동기 비동기

 

동기적 λΉ„동기적
νŽ˜μ΄μ§€λ₯Ό μƒˆλ‘œκ³ μΉ¨ν•˜λƒ μ•ˆ ν•˜λƒμ— λ”°λΌ λ‚˜λˆˆλ‹€,

call stack, task queue μ΄λ•Œ task queueλŠ” λΉ„λ™κΈ°μ μœΌλ‘œ μž‘동할 λ•Œ μ˜ˆλ₯Όλ“€μ–΄ API인 setTimeout μ•ˆμ— first ν•¨μˆ˜κ°€ μžˆλ‹€λ©΄ callbackμ—μ„œ λ°”λ‘œ task queue둜 λ“€μ–΄κ°„λ‹€.

ex) function first() { console.log('first() called'); }
function second() { setTimeout(() => console.log('second() called'), 1000); }
function third() { console.log('third() called'); }

first();
second();
third();

//
//ν˜„μž¬ μ‹€ν–‰ μ€‘인 μž‘업이 μ•„직 μ’…λ£Œλ˜μ§€ μ•Šμ€ μƒνƒœλΌκ³  ν•΄λ„, λ‹€μŒ μž‘업을 κ³§λ°”λ‘œ μˆ˜ν–‰ν•  μˆ˜ μžˆλŠ” λ°©μ‹


function first() {
    console.log('first() called');
}

function second() {
    console.log('second() called');
}

setTimeout(first, 3 * 1000);
second();

//
function first() {
    console.log('first() called');
}

function someLongWork() {
    console.log('였래 κ±Έλ¦¬λŠ” μž‘μ—… μˆ˜ν–‰ μ€‘...');
}

function second() {
    console.log('second() called');
}

first();
someLongWork();
second();

 

μ‹€μŠ΅ 링크

https://www.jsv9000.app/