Keeping in view the importance of fetch() method, this post aims to serve the following outcomes:
The detailed working flow of the fetch() method is explained below.
The fetch () method takes file path as a parameter. When this method executes, it returns a promise (a promise is just like a state), a promise is either successful or failed.
If the promise is successful, we use the then() function with the fetch() method.
After that, we create a function in which we get a response from the server as a parameter inside the function. The server sends a data file which is then sent as a response.
The first then() function also returns a promise, and this promise is used in the second then() function.
The result from the server is displayed inside the second then() function’s body. Here res_variable represents the variable that contains an actual result that is displayed to the user.
In the above syntax, file/URL represents the path of the server-side language file. The resp_variable denotes the response of the server when the fetch method requests the path. The res_variable represents the variable that stores the final response after the resp_variable function is executed and the err_variable represents the variable that stores an error if it occurs.
The catch() function is used to handle errors when the server is not responding or the file, we are sending contains errors.
In this code fetch method requests a read.txt file after that then() function gets the server response and returns it to the server again. Lastly, we again use the then() function to display the result.
The above output shows that the fetch() method requests a read.txt file and gets a fulfilled promise in return. After that the then() function uses this promise and gets the server response and uses it inside its body to return the response along with the text() method. Lastly, the second then() method gets the result and displays the content of the read.txt file.