最も簡単な非同期処理

let n = 0;

setInterval(() => {
    console.log(n % 2 === 0 ? "tick" : "tack");
    n++;
}, 1000);

コールバック地獄

const messages = ["おはよう", "こんにちは", "さようなら", "おやすみ"];

let index = 0;
setTimeout(() => {
    console.log(messages[index++]);
    setTimeout(() => {
        console.log(messages[index++]);
        setTimeout(() => {
            console.log(messages[index++]);
            setTimeout(() => {
                console.log(messages[index++]);
            }, 1000);
        }, 1000);
    }, 1000);
}, 1000);

Promiseによる書き換え

const messages = ["おはよう", "こんにちは", "さようなら", "おやすみ"];

let index = 0;
function delayMessage(resolve) {
    setTimeout(() => {
        console.log(messages[index++]);
        resolve();
    }, 1000);
}

function showMessages() {
    new Promise(delayMessage)
        .then(() => new Promise(delayMessage))
        .then(() => new Promise(delayMessage))
        .then(() => new Promise(delayMessage));
}

Promiseを返すAPI

const messages = ["おはよう", "こんにちは", "さようなら", "おやすみ"];

let index = 0;
function delayMessage() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(messages[index++]);
            resolve();
        }, 1000);
    });
}

function showMessages() {
    delayMessage().then(delayMessage).then(delayMessage).then(delayMessage);
}

showMessages();

async・awaitによる書き換え