2020년 5월 7일 목요일

Javascript 비동기 Code

Javascript 비동기 Code

JavaScript 프로그램은 단일 스레드이며 모든 코드는 병렬이 아닌 순서대로 실행된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
const second = () => {
    console.log('Second');
  }
const first = () => {
    console.log('First');
    second();
    console.log('The End');
  }
first();
//Results
First
Second
The End
cs


Callbacks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const second = () => {
   setTimeout(() => {
      console.log('Second Async');
   }, 2000);
}
const first = () => {
   console.log('First');
   second();
   console.log('The End');
}
first();
//Results
First
The End
Second Async
cs


Callback Hell
1
2
3
4
5
6
7
8
9
10
11
12
13
function getData() {
    setTimeout(() => {
      getData1();//Async Call.
      setTimeout(() => {
        getData2();//Async Call. 
        setTimeout(() => {
          getData3();
          console.log("Callback Hell");
             }, 1500);
        }, 1500);
    }, 1500);
}
getData();
cs


Promises
Promises로 이 콜백을 모두 피할 수 있고 비동기 JavaScript를 사용할 때 더 좋고 깔끔한 구문을 가질 수 있다 . Promises는 특정 이벤트가 이미 발생했는지 여부를 추적하는 객체이며, 발생했을 경우 다음에 어떤 일이 발생 하는지를 결정한다.

Promises는 다른 상태를 가질 수 있다. 이벤트가 발생하기 전에 Promises는 보류 중이다. 그런 다음 event가 발생된 후 promise는 settled or resolved 가 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function onSuccess () { 
  console.log ( 'Success!'
function onError () { 
  console.log ( 'Fail'
const p = new Promise ((해결, 거부) => { 
  setTimeout (() => { 
    resolve () 
  }, 2000
}) 
p.then (onSuccess) .catch (onError)
// fetch API
fetch('/api/user.json')   
  .then((response) => response.json())   
  .then((user) => {     
     // user is now ready to go.  
 })
cs


Async/Await
ES8 or ES2017 이후에 지원
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async function getPromise(){
   const data = await getData();
}
getPromise()
 
 
async function add (x, y) {  
      return x + y 
}  
add(2,3)
.then((result) => {
   console.log(result) // 5 
})
 
 
try{
  async function add (x, y) {  
      return x + y 
  }  
  add(2,3)
   .then((result) => {
     console.log(result) // 5 
   })
}catch(e){
   console.log(e)
}
cs


댓글 없음:

댓글 쓰기