fetch(): The fetch method gives a promise. It returns a response object
fetch function is a promise. When this promise is resolved then it gives you a response object, and the response object has a body which is a readable stream. If you convert this to JSON by using the .json method, then the .json method is also a promise, and when this promise is resolved, it gives you the actual value
Fetch with Error handling:
async function getData() {
try{
const promise = await fetch("<https://api.github.com/users/ShivajiKS>");
const data = await promise.json();
console.log(data);
}
catch(error){
console.log(data);
}
}
getData();
Why fetch?
1) Native support and docs
2) No installation required
3) Modern support
4). modern syntax(promise).
old error handling approach (promise then ):
async function getData() {
const promise = await fetch("<https://api.github.com/users/ShivajiKS>");
const data = await promise.json();
console.log(data)
}
}
getData().catch(error=>{
console.log(data);
});
Interview question :
1) What is async and await?
ans: async is a keyword that is used before a function to create an asynchronous function.
Async function will always return a promise, It can be either a promise object or a value like a string or a number etc. Suppose if you return a normal value,, then it basically takes this value and wraps it inside a promise objec,t, and it will return it.
await can be used only inside the async functions.