JavaScript でHTMLページのソースを取得する

async/await を使う場合は次のような感じ。async 関数はプロミスを返すので、受け取り側で値を取るときには、.then で受け取ればいい🧐

async function GetHtml(url) {
  const promise = fetch(url)            // Promiseを返す
  const response = await promise;       // fetch が確定するまで待機
  return response.text();               // Text表現の解析結果を値としてプロミス返す
}

console.log('foo');
GetHtml('https://bootcamp.fjord.jp/')
.then((text) => console.log(text));     // async はプロミスを返すので .then で受け取る
console.log('hoge');

実行結果は、GetHtml が非同期なので次のような感じになる。

foo
hoge
HTMLの内容(https://bootcamp.fjord.jp/のHTML)

async/await を使わずに書く場合は、次のように書けば同じ結果を得られる。

console.log('foo');
fetch('https://bootcamp.fjord.jp/')
.then((response) => {
    return response.text();
})
.then((text) => {
    console.log(text);
})
console.log('hoge');