'밤나무 아래'의 재생을 예로 들면 async의 비동기 처리를 설명한다.

10215 단어 aysncJavaScript

비동기 처리


프로그램이 실행된 후, 코드는 위에서부터 순서대로 한 줄 한 줄 실행된다.
만약 처리 중 시간이 걸리는 처리가 있다면, 실행이 끝날 때까지 다음 줄에 들어가지 않을 것입니다.
예를 들어 오선보를 통해 피아노의 소리 파일을 재생할 때 소리 파일을 하나하나 재생해야 한다.이 경우 동기화 처리만 가능하며 비동기 처리가 필요합니다.

왜 Async를 이용하세요?


ES6 이전의 비동기식 처리는 매우 번거로웠다.JavaScript에서는 흔히 이른바 호출 지옥에 빠진다.
ES6부터 Promise를 활용해 비동기 처리를 간결하게 썼다.

이른바 async


비동기 함수를 정의하는 함수 설명입니다.
함수 앞에서 async를 설명하면 비동기 함수 (async function) 를 정의할 수 있습니다.
・ async function이 호출되면 Promise로 돌아갑니다.
・async function에서 값을 반환할 때 Promise는 반환값을 resolve합니다.
• async function 예외 또는 throw 인 경우 이 값을 reject로 설정합니다.

async의 이용 예


다음은 노래'밤 아래'의 재생을 예로 들어 비동기 처리를 시도해 봤다.
#async.html
<script language="javascript">
    const playMusic = async function() {
        //大きな栗の木下で
        await play(4, 1).then((p) => { console.log("await:" + p);});
        await play(8, 1).then((p) => { console.log("await:" + p);});
        await play(8, 2).then((p) => { console.log("await:" + p);});
        await play(8, 3).then((p) => { console.log("await:" + p);});
        await play(8, 3).then((p) => { console.log("await:" + p);});
        await play(4, 5).then((p) => { console.log("await:" + p);});
        await play(8, 3).then((p) => { console.log("await:" + p);});
        await play(8, 3).then((p) => { console.log("await:" + p);});
        await play(8, 2).then((p) => { console.log("await:" + p);});
        await play(8, 2).then((p) => { console.log("await:" + p);});
        await play(2, 1).then((p) => { console.log("await:" + p);});
    }

    //signature:2→二分符、4→四分符、8→八分符
    //note:1→ド、2→レ、3→ミ、5→ソ
    const play = function(signature, note) {
        return new Promise((resolve, reject) => {
            let waitTime = signature * 500;
            //let mp3FileNm =getMp3FileNm();
            //mp3音声ファイルを再生する
            //play(mp3FileNm);
            console.log("play");
            let p = "signature:" + signature + " note:" + note;
            setTimeout(resolve, waitTime, p);
        });
    }   
</script>
실행 결과:

좋은 웹페이지 즐겨찾기