JSFiddle - React, Tailwind, and code Playground
HTML
<p>Click the button repeatedly and observe the outcomes in browser's console.</p>
<p>In the case of an error, the log will show which of the three async calls failed.</p>
<button id="go">Go</button>
<p><i>An error should occur approximately 7 times in every 8 goes.</i></p>
JavaScript
function doSomethingAsync(x) {
return new Promise(function(resolve, reject) {
if(Math.random() > 0.5 ) {
resolve(x);
} else {
reject(x);
}
});
}
function doAnAsyncSequence() {
return Promise.resolve()
.then(function() {
return doSomethingAsync('one');
})
.then(function() {
return doSomethingAsync('two');
})
.then(function() {
return doSomethingAsync('three');
});
}
$("#go").on('click', function() {
doAnAsyncSequence().then(function(result) {
console.log('success: ' + result);
}, function(reason) {
console.log('error: ' + reason);
});
});