JSFiddle - React, Tailwind, and code Playground
by brigand
HTML
<script src="https://cdn.jsdelivr.net/sweetalert2/latest/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/sweetalert2/latest/sweetalert2.min.css">
<p>
I'm looking to chain my requests. I need for the first request to start and finish before the next request is made.
</p>
<input type="checkbox" name="users[]" value="user1" checked>
<input type="checkbox" name="users[]" value="user2" checked>
<input type="checkbox" name="users[]" value="user3" checked>
<input type="checkbox" name="users[]" value="user4" checked>
<br>
<button id="go">go</button>
JavaScript
jQuery(document).ready(function() {
$('#go').on('click', function(event) {
// Second, third, etc. Each request needs to be executed when the previous request finishes.
const values = Array.from($('input[name="users[]"]:checked'), (el) => $(el).val());
const promise = values.reduce((previous, value) => previous.then((results) =>
fetch('/echo/html/?id=' + value, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
},
body: 'delay=3'
}).then(res => res.text())
.then(text => {
return results.concat([text])
})
), Promise.resolve([]))
promise.then(all => {
console.log(`all`, all)
})
});
swal.close();
});