I expected the output: A, B, C. But it doesn't work. Provided that the function handleClick(element) cannot be changed, how can I change the other functions to make sure that all code execute in sequence and output A, B, C as expected?
async function handleClick(element) {
setTimeout(function(){
console.log(`Click on Element_${element}`);
}
, Math.random(5)*1000);
}
async function clickLetter(letter) {
await handleClick(letter);
}
async function clickGroup(group) {
await handleClick(group);
}
const letters = ['A', 'B', 'C'];
function clickLetters(letters, fn) {
let index = 0;
return new Promise(function(resolve, reject) {
function next() {
if (index < letters.length) {
fn(letters[index++]).then(next, reject);
} else {
resolve();
}
}
next();
});
}
clickLetters(letters, clickLetter);
The setTimeout function is asynchronous and the result is returned immediately, you need to wrap this inside a promise constructor and then resolve it.
function handleClick(element) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`Clicked on Element_${element}`);
resolve();
}, Math.random(5) * 1000);
});
}
async function clickLetter(letter) {
await handleClick(letter);
}
async function clickGroup(group) {
await handleClick(group);
}
const letters = ['A', 'B', 'C'];
async function clickLetters(letters, fn) {
for(let i = 0; i < letters.length; i++) {
await clickLetter(letters[i]);
}
}
clickLetters(letters, clickLetter);
As mentioned, the async library is/was a way to do it.
If you want to keep going with your current solution, the problem was in your handleClick() where the implicit promise was returning immediately, before the timeout. Then, depending on the random timeout for each pass, it would result in an out or ordr execution. The fix is just resolve the promise then it times out.
function handleClick(element) {
return new Promise(resolve => {
setTimeout(function(){
console.log(`Click on Element_${element}`);
resolve();
}
, Math.random(5)*1000);
});
}
async function clickLetter(letter) {
await handleClick(letter);
}
function clickLetters(letters, fn) {
let index = 0;
return new Promise(function(resolve, reject) {
function next() {
if (index < letters.length) {
fn(letters[index++]).then(next, reject);
} else {
resolve();
}
}
next();
});
}
const letters = ['A', 'B', 'C'];
clickLetters(letters, clickLetter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With