Load data asynchronously and handle HTTP errors and cancellation.

Before starting: JavaScript promises and JSON.

Practice project: Extend the examples into a small Ajax and Fetch study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. Fetch: load data without reloading the page

    Ajax describes updating a page using background requests. Fetch is a browser API commonly used for this. A fulfilled fetch promise can still carry an HTTP error, so check response.ok.

    Modern browser on a local HTTP server. Create learner.json containing {"name":"Asha"} alongside the page.

    async function loadLearner() {
      const response = await fetch("./learner.json");
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const data = await response.json();
      console.log(data.name);
    }
    loadLearner().catch(error => console.error(error.message));
    Check the output
    Asha when the supplied file is served successfully. Otherwise an error is reported.

    Request a missing file and confirm that the error path runs.

  2. Fetch: cancel an unwanted request

    AbortController lets a caller cancel a request it no longer needs. Cancellation is not evidence of a server failure. Handle it separately from other errors.

    Modern browser on a local HTTP server. Create learner.json containing {"name":"Asha"} alongside the page.

    const controller = new AbortController();
    fetch("./learner.json", {signal: controller.signal})
      .catch(error => console.log(error.name));
    controller.abort();
    Check the output
    For the immediately aborted request, the rejection is reported as AbortError.

    Explain when switching search terms should cancel a previous request.

Open the AJAX learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.