Async fetch cancel

by jib1

HTML

Rapid search using fetch(url, {cancel: promise})
<input id="input"></input>
<div id="div"></div>
<script src="https://rawgit.com/jan-ivar/cancel/master/cancel.js"></script>

JavaScript

input.once = function(type) {
  return new Promise(resolve => this.addEventListener(type, function f(e) {
    this.removeEventListener(type, f);
    resolve(e);
  }));
};

input.oninput = async ({target: {value: term}}) => {
  console.log(`searching for "${term}"`);
  try {
    let response = await fetch("/echo/json/", {
      method: "post",
      body: "json=" + encodeURI(JSON.stringify({result: term.toUpperCase()})) + "&delay=1",
      cancel: input.once("input")
    });
    let {result} = await response.json();
    console.log(`results for "${term}" ` + result);
  } catch (e) {
    if (e.name != "CancelError") throw e;
  }
};

var console = { log: msg => div.innerHTML += msg + "<br>" };