Promise Rejection Chains
Trying to illustrate the idea of promise rejection chains
by Admiral Potato
HTML
<div id="app">
<h2>Error types:</h2>
<ol>
<li
v-for="type in errorTypes"
:key="type"
>
<button
@click="asyncThrow(type)"
>
{{type}}
</button>
</li>
</ol>
<h2>Message: {{message}}</h2>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
const promiseHandle = (type, successHandler) => {
return new Promise((resolve, reject) => {
if (type === 'success') {
resolve(type);
} else {
reject(new Error(type));
}
})
.then(successHandler)
.catch((error) => {
if(error.message === 'a') {
return 'error type a handled';
} else {
throw error;
}
})
.catch((error) => {
if(error.message === 'b') {
return 'error type b handled';
} else {
throw error;
}
})
.catch((error) => {
if(error.message === 'c') {
return 'error type c handled';
} else {
throw error;
}
});
}
new Vue({
el: "#app",
data: {
message: '',
errorTypes: [
'a',
'b',
'c',
'd',
'success'
]
},
methods: {
asyncThrow: function(type){
promiseHandle(type, (type) => {
return `"${type}" happened`
})
.then((result) => {
this.message = result;
})
.catch((error) => {
this.message = 'unhandled error type: ' + error.message;
});
}
}
})