Promise in JS got three states – resolve, reject and pending. Following example shows a reject state.
promise = new Promise((resolve, reject) => {
reject();
});
promise
.then(() => {console.log('finally finished')})
.then(() => {console.log('i was also ran')})
.catch(()=> {console.log('catch rejected')})
Output
//catch rejected
Another example with resolve status
promise = new Promise((resolve, reject) => {
resolve();
});
promise
.then(() => {console.log('finally finished')})
.then(() => {console.log('i was also ran')})
.catch(()=> {console.log('catch rejected')})
//Output
finally finished
i was also ran
promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 3000);
});
promise
.then(() => {
console.log('finally finished')
})
.then(() => {
console.log('i was also ran')
})
.catch(() => {
console.log('catch rejected')
})
//Output after 3 seconds.
finally finished
i was also ran
Type the below in Chrome console and you will get the response in JSON format.
url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
.then(response =>response.json())
.then(data =>console.log(data));