title: Javascript, async, lock?
body: <p>I know async is not parallel but I bumped into a quite funny situation now.</p>
  
  <pre><code>async function magic(){
    /* some processing here */
    await async () =&gt; await prompt_for_user(); // 1st prompt
    await async () =&gt; await prompt_for_user(); // 2nd prompt
  }
  
  magic(); // first
  magic(); // second
  magic(); // third
  </code></pre>
  
  <p>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:</p>
  
  <pre><code> const Queue = () =&gt; {
    let promise;
    return async (f) =&gt; {
      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 () =&gt; await prompt_for_user()); // 1st prompt
    await queue(async () =&gt; await prompt_for_user()); // 2nd prompt
  }
  
  magic(); // first
  magic(); // second
  magic(); // third
  </code></pre>
  
  <p>This stops the prompt from popping up all at a time. But there is a second problem:</p>
  
  <p>So when the first <code>magic()</code> is called. A prompt <code>first.1</code> is shown to the user. The program continues and the second <code>magic()</code> is called. Another prompt <code>second.1</code> is awaiting for the first prompt to finish before showing up. Then the program continues, the third <code>magic()</code> is called and <code>third.1</code> again awaits for <code>first.1</code> to finish. When <code>first.1</code> finishes, meaning the user have typed the value, <code>second.1</code> will pop up first but I wish <code>first.2</code> to pop up first.</p>
  
  <p>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.</p>
  
  <p>Idea?</p>