Home > Web Front-end > JS Tutorial > How to write Simple Endpoint and Functions

How to write Simple Endpoint and Functions

Linda Hamilton
Release: 2025-01-12 16:28:43
Original
340 people have browsed it

A month ago I’ve joined KarmanX and where I learnt about how to write simple to advanced level of functions and its endpoints. I’ve got an opportunity to attend the Ankita Mam’s Session, where she explained how to write simple and complex functions and how the API call works, so here I’m going to explain in short how to think and write this functions.

How to write Simple Endpoint and Functions

From the above dig. in simple terms we can say that the client is requesting to server, to extract the data from movie database but now think like a developer perspective. Here we know, the client is requesting to server, to get or to extract all movies from database. From this line we can get some idea for how to send request.

Basically app.get(‘/movies’,async(req,res)=>{}) is requesting to server to get this movie data whenver user writes ‘/movies’. Inside the try block I’ve declared result variable where I’m calling a function which extract all the movies. Here we are using try-catch block for error handling.

I’ve declared a function getAllMovies which returns movies. Inside the try block I’ve written if the movies are not present in the movie database [i.e I’m checking the length of the result], it will throw an error 404 with a message ‘No movies found!’. If the movies are present in the datbase, then it will respond with result.

In the catch block if any internal error is there then it will throw an error 500 with a message internal server error. Here I’ve used async-await. The keyword async before a function makes the function return a promise and the await keyword can only be used inside the async function. The await keyword makes the function pause the execution and wait for resolved promise.

The above is the detailed content of How to write Simple Endpoint and Functions. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template