<button type="button" data-task="{..task..}" data-post="{...{}..{}..}">Btn 1 2</button>
<button type="button" data-task="{..task..}">Btn 1</button>
<button type="button" data-post="{...{}..{}..}">Btn 2</button>
$('[data-task]').click(function(event) {
// wait if btn has other async task to complete
//then do task stuff
});
$('[data-post]').click(function(event) {
//lock or something
$.ajax({
//post stuff
}).done(function (data) {
//release lock
});
});
Here, ajax will take a second but data-task will be executed instantly.
I can do it for sync task in this way,
$('[data-task1],[data-task2]').click(function(event) {
if($this.data("task1")){
//first stuff
}
if($this.data("task2")){
//second stuff
}
});
but dont know how to do it for asyc like ajax
Is there a way I can lock all other process of this click until ajax is completed?
>Solution :
You can add another data-attribute for exclude multiple function from the singol task button then use async/await like:
$('[data-task]:not([data-multiple])').click(function(event) {
console.log('just task');
});
$('[data-post]:not([data-multiple])').click(function(event) {
console.log('just post');
});
$('[data-multiple]').click(async function(event) {
const resultTask = await doTask();
console.log(resultTask);
const resultPost = await doPost();
console.log(resultPost);
});
//fake request
function doTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("task completed");
}, 1000);
});
}
function doPost() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("post completed");
}, 1000);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" data-task="{..task..}" data-post="{...{}..{}..}" data-multiple>Btn 1 2</button>
<button type="button" data-task="{..task..}">Btn 1</button>
<button type="button" data-post="{...{}..{}..}">Btn 2</button>
You can use ajax too for the request see that link