0
const x = Promise.race([
        new Promise(resolve => { while(true);}),
        new Promise(resolve => { let i = 0; while((i++)<100);console.log(2); resolve(); }),
        new Promise(resolve => { let i = 0; while((i++)<2000);console.log(3); resolve(); }),
        ]);
console.log('This line ran');

I thought promises are asynchronous.But the code above doesn't print anything.

I tried replacing Promise.race() with Promise.all() yet no output.

  • 1
    JavaScript is single-threaded. Asynchronous does not mean parallel execution. – freedomn-m Jul 06 '23 at 10:31
  • 3
    "I thought promises are asynchronous" — No, they are tools to manage code that is already asynchronous. – Quentin Jul 06 '23 at 10:31
  • 2
    Asynchronous does not automatically mean multi-threaded or preemptive multitasking. JavaScript code only allows cooperative multitasking (yield, await, ...) and multiprocessing (workers). – t.niese Jul 06 '23 at 10:32
  • 1
    The first promise will never yield, so nothing else gets a chance to run. – phuzi Jul 06 '23 at 10:32
  • Written for C#, but relevant here https://stackoverflow.com/questions/34680985/what-is-the-difference-between-asynchronous-programming-and-multithreading/34681101#34681101 – Jared Smith Jul 06 '23 at 13:49
  • Promises are a **design pattern** to handle asynchronous event. A `Promise` itself is just a class. You can implement `Promise` yourself in pure javascript without writing any system code (indeed, people used to implement their own promise libraries like `bluebird` and `q` before it got standardised) - it is after all just a design pattern, not a language feature. – slebetman Jul 06 '23 at 13:50

0 Answers0