I know async is not parallel but I bumped into a quite funny situation now.
async function magic(){
/* some processing here */
await async () => await prompt_for_user(); // 1st prompt
await async () => await prompt_for_user(); // 2nd prompt
}
magic(); // first
magic(); // second
magic(); // third
From the program above, we could easily predicts that all prompts pops up together at the same time. I tried to solve it with a queue with the following implementation:
const Queue = () => {
let promise;
return async (f) => {
while(promise) await promise;
promise = f();
const res = await promises;
promise = undefined;
return res;
};
};
const queue = Queue();
async function magic(){
/* some processing here */
await queue(async () => await prompt_for_user()); // 1st prompt
await queue(async () => await prompt_for_user()); // 2nd prompt
}
magic(); // first
magic(); // second
magic(); // third
This stops the prompt from popping up all at a time. But there is a second problem:
So when the first magic() is called. A prompt first.1 is shown to the user. The program continues and the second magic() is called. Another prompt second.1 is awaiting for the first prompt to finish before showing up. Then the program continues, the third magic() is called and third.1 again awaits for first.1 to finish. When first.1 finishes, meaning the user have typed the value, second.1 will pop up first but I wish first.2 to pop up first.
I know one obvious solution would be await the magic one by one. But this would lose the asynchronous advantages that js gives us. If the processing is heavy in magic before prompting, it will take some time before prompting.
Idea?
awaits those will always come after the other async calls (just purely because that's the order the compiler sees them) i.e. first async starts and run loop starts to process other sync code, which will fire the other prompts. You're at the mercy of the run loop / internal prioritisation here.