Roberta  Ward

Roberta Ward

1599370020

Fetch with async & await and TypeScript

The fetch API is a native JavaScript function that we can use to interact with web services. How can we use fetch with async and await? and how can we use this with TypeScript to get a strongly-typed response? Let’s find out …

image by Jozef Fehér on www.pexels.com

Making a simple request

fetch supports async and await out of the box:

const response = await fetch(
  "https://jsonplaceholder.typicode.com/todos"
);

So, we simply put the await keyword before the call to the fetch function.

We’re using the fantastic JSONPlaceholder fake REST API in the example consuming code.

To get the response body, we call the responses json method:

const body = await response.json();

Notice that we use the await keyword before the method call because it is asynchronous.

Creating a utility function

Let’s create a function that we can call that combines these two lines of code and returns the response body:

export async function http(
  request: RequestInfo
): Promise<any> {
  const response = await fetch(request);
  const body = await response.json();
  return body;
}

// example consuming code
const data = await http(
  "https://jsonplaceholder.typicode.com/todos"
);

So, we can use our new function to make a request and get the response body in a single line of code. Neat!

Typed response data

Notice that we typed the response body to any in the above example. Let’s make this a little more strongly-typed:

export async function http<T>(
  request: RequestInfo
): Promise<T> {
  const response = await fetch(request);
  const body = await response.json();
  return body;
}

// example consuming code
interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

const data = await http<Todo[]>(
  "https://jsonplaceholder.typicode.com/todos"
);

So, our http function now takes in a generic parameter for the type of the response body. In the consuming code, our data variable is strongly typed to Todo[].

#typescript

What is GEEK

Buddha Community

Fetch with async & await and TypeScript

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

Code  JS

Code JS

1654326531

JavaScript Fetch API Explained | Callbacks, Promises, Async Await

Learn about Callbacks, Promises, and Async Await as the JavaScript Fetch API is explained in this tutorial. You will also learn about thenables and how async / await replaces them in our JS code. The first 30 minutes covers the concepts. The last 30 minutes gives examples of retrieving data from different APIs with Fetch.

Quick Concepts outline:
Fetch API with Async / Await
(0:00) Intro
(0:29) What is a callback function?
(1:15) What is the problem with callbacks?
(3:00) JavaScript Promises have 3 states
(5:28) A promise may not return a value where you expect it to: You need to wait for a promise to resolve
(6:58) Using thenables with a promise
(20:15) An easy mistake to make with promises
(24:00) Creating an async function
(25:00) Applying await inside the function
(33:45) Example 1: Retrieving user data
(40:00) Example 2: Retrieving dad jokes
(47:00) Example 3: Posting data
(49:40) Example 4: Retrieving data with URL parameters
(54:55) Abstract it all into single responsibility functions

Subscribe: https://www.youtube.com/c/DaveGrayTeachesCode/featured 

#async  #await  #fetch #javascript 

Rusty  Bernier

Rusty Bernier

1592372285

Two Ways to Do Async/Await in ASP.NET Wrong (and How to Fix Them)

My team is in the process of refactoring a large application that we want to deploy to our production environment soon. I’ve just been assigned as lead developer to this project, since the prior lead got another job in a different state, and I’ve been digging through the code to

#async/await #async #asp.net #programming

Roberta  Ward

Roberta Ward

1599370020

Fetch with async & await and TypeScript

The fetch API is a native JavaScript function that we can use to interact with web services. How can we use fetch with async and await? and how can we use this with TypeScript to get a strongly-typed response? Let’s find out …

image by Jozef Fehér on www.pexels.com

Making a simple request

fetch supports async and await out of the box:

const response = await fetch(
  "https://jsonplaceholder.typicode.com/todos"
);

So, we simply put the await keyword before the call to the fetch function.

We’re using the fantastic JSONPlaceholder fake REST API in the example consuming code.

To get the response body, we call the responses json method:

const body = await response.json();

Notice that we use the await keyword before the method call because it is asynchronous.

Creating a utility function

Let’s create a function that we can call that combines these two lines of code and returns the response body:

export async function http(
  request: RequestInfo
): Promise<any> {
  const response = await fetch(request);
  const body = await response.json();
  return body;
}

// example consuming code
const data = await http(
  "https://jsonplaceholder.typicode.com/todos"
);

So, we can use our new function to make a request and get the response body in a single line of code. Neat!

Typed response data

Notice that we typed the response body to any in the above example. Let’s make this a little more strongly-typed:

export async function http<T>(
  request: RequestInfo
): Promise<T> {
  const response = await fetch(request);
  const body = await response.json();
  return body;
}

// example consuming code
interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

const data = await http<Todo[]>(
  "https://jsonplaceholder.typicode.com/todos"
);

So, our http function now takes in a generic parameter for the type of the response body. In the consuming code, our data variable is strongly typed to Todo[].

#typescript