In JavaScript, we can use the Fetch API to make network requests and receive a Promise object in return. The Promise object represents the eventual completion (or failure) of an asynchronous operation, and provides methods for handling success and error cases.
Here's an example of how to fetch data using the Fetch API:
index.tsx167 chars5 lines
This code snippet makes a GET request to the JSONPlaceholder API to fetch a single post. The response is returned as a Promise, which we can then chain together with .then()
and .catch()
to handle the result.
Alternatively, we can use async/await
syntax to write more concise and readable code:
index.tsx247 chars12 lines
In this example, we define an async
function that fetches the post data using await
syntax. The try/catch
block allows us to handle success and error cases in a cleaner and more maintainable way. Note that we need to call the fetchPost()
function to kick off the asynchronous operation.
gistlibby LogSnag