Asynchronous Javascript

  • 비동기 관련 함수
    • ES5 : callback
    • ES6 : promise
    • ES7 : async/await
  • (비동기 개념)[https://developer.mozilla.org/ko/docs/Learn/JavaScript/Asynchronous/Concepts){:target=”_blank”}
  • (동기식처리 예제)[:https://github.com/mdn/learning-area/blob/master/javascript/asynchronous/introducing/simple-sync-ui-blocking.html]{:target=”_blank”}
  • 가장 기본적인 형태의 JavaScript는 한 번에 하나의 작업만 진행할 수 있는 동기식 차단 단일 스레드 언어입니다. 그러나 웹 브라우저는 어떤 종류의 이벤트(시간 경과, 사용자와 마우스의 상호 작용 또는 데이터 도착 예를 들어 네트워크를 통해). 즉, 메인 스레드를 중지하거나 차단하지 않고 코드에서 동시에 여러 작업을 수행할 수 있습니다.

callback

const selectUrl = "http://localhost/prj/todoSelect";
const insertUrl = "http://localhost/prj/todoInsert?contents=xhr";

function ajax1(){
    const xhttp = new XMLHttpRequest();  // ※ 비동기 ※
    xhttp.onload = function() {
        console.log("insert", this.responseText);   //1
        const xhttp1 = new XMLHttpRequest();  // ※ 비동기 ※
        xhttp1.onload = function() {
            console.log("select", this.responseText);   //1
        }
        xhttp1.open("GET", selectUrl);
        xhttp1.send();
    }
    xhttp.open("GET", insertUrl);
    xhttp.send();
}

promise

참고사이트 : https://developer.mozilla.org/ko/docs/Learn/JavaScript/Asynchronous/Concepts

  • 콜백지옥을 벗어나자
function ajax2() {
    fetch(insertUrl)
    .then(data=>data.json())
    .then(function(datas){
        console.log("insert", datas);   
        return fetch(selectUrl);   })
    .then(data=>data.json())    
    .then(data=>console.log("select", data)  )
}

async/await

  • 비동기처리를 동기처리처럼 동작하도록 구현
  • promise를 기반으로 동작
  • 프로미스의 후속처리 메서드 없이 마치 동기 처리처럼 프로미스가 처리결과를 반환하도록 구현
async function ajax3(){
    let data = await fetch(insertUrl);   //동기식(블록킹함수)
    let result = await data.json(); 
    console.log("insert", result); 

    data = await fetch(selectUrl);
    result = await data.json();
    console.log("select", result);
}

Categories:

Updated: