asyncとawaitを使った非同期処理

Wikipediaで検索する

headに書くこと

//特になし

JavaScriptで書くこと

(() => {
 
  const wikiInput = document.getElementById("js-wikipedia-input");
  const wikiButton = document.getElementById("js-wikipedia-button");
  const wikiBody = document.getElementById("js-wikipedia-body");

  const wikiFetch = async (inputValue) => {
    const fetchValue = fetch(`https://ja.wikipedia.org/w/api.php?format=json&action=query&origin=*&list=search&srlimit=45&srsearch=${inputValue}`, {
      method: "GET"
    })
      .then((value) => {
        return value.json();
      })
      .catch(() => {
        alert("wikipediaにうまくアクセスできないようです、、");
      });
    const valueJson = await fetchValue;
    const valueTargets = valueJson.query.search;
    if (!valueTargets.length) {
      const wikiNull = document.createElement("p");
      wikiNull.classList.add("p-wikipedia__null");
      wikiNull.textContent = "検索したワードはヒットしませんでした。";
      wikiBody.appendChild(wikiNull);
    } else {
      const elemWrap = document.createElement("div");
      elemWrap.classList.add("p-wikipedia__main");

      for (const elem of valueTargets) {
        const elemBlock = document.createElement("a");
        elemBlock.classList.add("p-wikipedia__block");
        elemBlock.setAttribute("target", "_blank");
        elemBlock.setAttribute("rel", "noopener noreferrer");
        const elemId = elem.pageid;
        elemBlock.setAttribute("href", `http://jp.wikipedia.org/?curid=${elemId}`);

        const elemSpan = document.createElement("span");
        elemSpan.classList.add("p-wikipedia__block-ttl");
        const elemTitle = elem.title;
        elemSpan.textContent = elemTitle;

        const elemSpan2 = document.createElement("span");
        elemSpan2.classList.add("p-wikipedia__block-date");
        const elemDate = elem.timestamp;
        const elemDateSlice = elemDate.slice(0, 10).replace(/-/g, ".");

        elemSpan2.textContent = "最終更新日:" + elemDateSlice;

        elemWrap.appendChild(elemBlock);
        elemBlock.appendChild(elemSpan);
        elemBlock.appendChild(elemSpan2);
        wikiBody.appendChild(elemWrap);
      }
    }
  };
  const wikiData = () => {
    wikiBody.innerHTML = "";
    const inputValue = wikiInput.value;
    wikiFetch(inputValue);
  };

  wikiButton.addEventListener("click", wikiData, false);
})();

CSSで書くこと

/*-- 省略 --*/

HTMLで書くこと

<div class="p-wikipedia">
     <div class="p-wikipedia__inner">
            <h3 class="p-wikipedia__heading">Wikipediaで検索する</h3>
            <div class="p-wikipedia__search">
                <input id="js-wikipedia-input" type="text" value="" placeholder="検索ワード">
                <button id="js-wikipedia-button" type="button">検索</button>
            </div>
            <div class="p-wikipedia__body" id="js-wikipedia-body"></div>
     </div>
 </div>