Application Programming Interface (API) : It acts like a bridge between frontend and backend where backend sends the data to frontend by endpoints.
eg: Swiggy gets google location or netflix gets geolocation
APIs are used for typically http request such as GET, POST, PUT, DELETE, etc...
How to use APIs?
In olden times, we used to work with APIs using XHR(Xml Http Request), but now browsers have default method called fetch which also works XHR underneath.
Fetch: Fetch is a web API (given by browers is called web api) which is used for http request. Fetch returns promise. Promise is an object which have three states (pending, fullfilled, rejected) and it describes eventual completion of asynchronous operation.
Promises are resolved by then and catch blocks. Fullfilled state of a promise triggers then block and rejected state of a promise triggers catch block
eg: fetch(url)
.then(function(res) {
//success code of a promise with "res" we can give any name response
})
.catch(function(err){
//rejected code of a promise with 'err' error
})
Promises can be combined one after the other called promise chaining
eg: Promise
.then(() => newPromise)//what ever this promise returns another promise takes it and resolves it until all promises resolves it will chain called promise chaining like default of swich case
.then(() => resolve)
.catch(() => catchLogic)
Top comments (0)