Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fetch('https://api-to-call.com/endpoint') //first argument determines the endpoint of the request.
- .then(response => { //.then() will fire only after the promise status of fetch() has been resolved.
- if (response.ok){
- return response.json(); //Testing the ok property of the response object that it will be a Boolean value. If there were no errors, response.ok will be true and the code will return
- }
- throw new Error('Request failed!'); //code will throw this error when response.ok is falsy.
- }, networkError => {
- console.log(networkError.message); //If we could not reach the endpoint at all, e.g., the server is down, then we would get this networkError.
- }).then(jsonResponse => { //The second .then()‘s success callback won’t run until the previous .then() method has finished running. It will also not run if there was an error was thrown previously.
- return jsonResponse;
- }
- );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement