We will illustrate the asynchronous nature of JavaScript and how we managed it using Promises.
I'm looking for contributions. Anyone interested in helping I have the folowing things that could be easy to contribut to:
promise_controller.spec.js
is especially weak at the moment.Check out the source on GitHub and contribute!
This demo generates data which are meant to simulate network latency. They are timed events that will resolve or reject based on a random setTimeout
.
The random timeout is anywhere between 500 ms to 10 seconds. Which means if we were to synchronously wait for 1000 workers then it could take up to 10,000 seconds! Using an asynchronous pattern the same data set can complete in just over 10 seconds!
This demo demonstrates this processing by displaying the resolved workers as they complete. Each worker has a random title and a unique ID. When it's random timer completes the data is displayed in the box associated with it's ID.
We construct boxes for each worker but leave it blank so you will see a grid of boxes and they will display a title and change color depending on the resolution of the worker. Either GREEN for resolved or in some random cases RED for rejected workers.
1 function normalFunction() { 2 if (condition) { 3 // this will mutate a wrapped promise by fulfilling it 4 return "value"; 5 } 6 else { 7 // this will mutate a wrapped promise by rejecting it 8 throw "reason"; 9 } 10 } 11 12 function callback(value) { 13 console.log(value); 14 } 15 16 function failed(reason) { 17 console.log(reason); 18 } 19 20 var promise = Q.fcall(normalFunction); 21 22 promise.then(callback); // => "value" 23 promise.fail(failed); // => "reason" 24 promise.then(callback, failed);