A Go-inspired approach to handling fetch API

WBOY
Release: 2024-08-23 08:30:31
Original
1126 people have browsed it

A Go-inspired approach to handling fetch API

Javascript error handling can sometimes be confusing especially in using fetch, if you are using await you will need to wrap it in a try catch block to handle the error and we all know that it's a headache

Well what if i tell you we can do something like this

import { get } from "./eavfetch";

interface Book {
  id: string;
  title: string;
  author: string;
}

async function fetchBooks() {
  // data type is inferred as Book[]
  const [data, error] = await get<Book[]>("/books");

  if (error) {
    console.error("Failed to fetch books:", error);
    return;
  }

  if (data) {
    console.log("Fetched books:", data);
  }
}
Copy after login

Now all of the sudden handling fetch seems easy and very straightforward and safe way to handle error and data right? Well that's the power of error as values approach

you can copy the eavfetch.ts/js in the repo and start using it right away.

The above is the detailed content of A Go-inspired approach to handling fetch API. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!