I'm relatively new to Promises in Javascript, but have recently fell in love with their elegance, particularly in the Bluebird library.
This is probably a newbie question, but how could I convert a normally-synchronous function to run asynchronously? If I, for example, wanted to compute Math.random()*RANGE
thirty times in-parallel, how exactly could I do that with promises (in either Q or Bluebird)?
First off, promises won't help you make code run in parallel. They are a tool for running other code when your task is done or coordinating this task with other tasks. But making your current code run in parallel with other code has nothing to do with promises.
Second off, there's little advantage (and a lot of complication) to taking a synchronous task and trying to make it work more like an asynchronous tasks unless it is so long running that it interferes with the responsiveness of other operations. Computing a set of random numbers is unlikely to be that long a running task.
If you truly want parallel execution in a browser, you would have go use WebWorkers which is the only way to create an truly independent execution thread in browser-based javascript. Other than WebWorkers, javascript in a browser is single threaded so there is no parallel execution. It is possible to execute small chunks of code on successive setTimeout()
calls which will interweave your code execution with other things going on in the browser and can allow other browser tasks to remain responsive while running another long running task.
You can see an example of processing a large array in chunks using setTimeout()
here Best way to iterate over an array without blocking the UI to allow other things to run in between chunks of processing. Promises could be added to something like this as a method of managing the completion of the task or managing its coordination with other tasks, but promises don't actually help you make it work in chunks.
You cannot. Promises don't "make code parallel", they just provide a better abstraction for asynchronous code - they don't have more power than callbacks.
A synchronous code will always be executed synchronously, and is - due to JavaScript's single-threaded nature - not parallelisable. Even if you give it a callback whose execution is deferred by the use of an actually async function, that will just defer the callback to a later event loop slice, but not make your synchronous task execute in parallel to anything else - and won't make it execute faster either. It only might help to break up long-running code into chunks (see here or here) which can make an app feel faster.
What you can do is execute the code on another thread (WebWorker, node cluster, …) and use events to pass the results back. For those events, you could code a nice promise abstraction; but seriously - the overhead of threads is much too large for just generating 30 random numbers.