Max Klymyshyn discusses various approaches for handling asynchronous JavaScript, including promises, generators, async/await, CSP channels using js-csp, and the actor model. He describes some of the key benefits of each approach, such as CSP channels solving problems of coordinating asynchronous components and CSP alongside other approaches solving the problem of easy-to-understand code. Klymyshyn also provides code examples for using many of these approaches.
12. Await
async function loadStory() {
try {
let story = await getJSON('story.json');
addHtmlToPage(story.heading);
for (let chapter of story.chapterURLs.map(getJSON)) {
addHtmlToPage((await chapter).html);
}
addTextToPage("All done");
} catch (err) {
addTextToPage("Argh, broken: " + err.message);
}
document.querySelector('.spinner').style.display = 'none';
}
(async function() {
await loadStory();
console.log("Yey, story successfully loaded!");
}());
[5] [6] [7]
13. FRP/RxJS
const $input = $('#input');
const $results = $('#results');
/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent($input, 'keyup')
.pluck('target', 'value')
.filter(text => text.length > 2 );
/* Now debounce the input for 500ms */
var debounced = keyups.debounce(500 /* ms */);
/* Now get only distinct values, so we eliminate the
arrows and other control characters */
var distinct = debounced.distinctUntilChanged();
[4]
14. Actormodel
(function () {
var spawn = WebActors.spawn;
var receive = WebActors.receive;
var send = WebActors.send, ANY = WebActors.ANY;
function aCallback() {
receive(ANY, function (message) {
alert(message);
});
}
actor = spawn(aCallback); // create an actor
send(actor, "a message"); // send it a message
})();
[2] [3]