I'm pretty new to promises, and came across something I was wondering about. Here is some simple fetch code, and in the .catch() block, we use e.message to log the "human-readable description of the error".
function fetchAndDecode(url, type) {
return fetch(url).then(response => {
if(!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
if(type === 'blob') {
return response.blob();
} else if(type === 'text') {
return response.text();
}
}
})
.catch(e => {
console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message);
})
Then, here's a user-made promise using the Promise() constructor as opposed to the fetch API, and in the .catch() block, e.message is undefined, and instead we have to use e.
function timeoutPromise(message, interval) {
return new Promise((resolve, reject) => {
if (message === '' || typeof message !== 'string') {
reject('Message is empty or not a string');
} else if (interval < 0 || typeof interval !== 'number') {
reject('Interval is negative or not a number');
} else {
setTimeout(function(){
resolve(message);
}, interval);
}
});
};
timeoutPromise('Hello there!', 1000)
.then(message => {
alert(message);
})
.catch(e => {
console.log('Error: ' + e); // e.message doesn't work here (it's undefined)
});
What is the reason for this? Do you simply use e.message with fetch and e for promises made using the Promise() constructor? Is it some other reason I'm overlooking?