FH-Potsdam / connecting-bits

A project of the seminar input output
ISC License
4 stars 1 forks source link

API for chaining different code-functionalities based on events or deffered #49

Closed vogelino closed 8 years ago

vogelino commented 8 years ago
vogelino commented 8 years ago

Interessant libraries that could solve the problem used: Event emitter looks like:

var ee = require('event-emitter');

var emitter = ee({}), listener;

emitter.on('test', listener = function (args) {
  // …emitter logic 
});

emitter.once('test', function (args) {
  // …invoked only once(!) 
});

emitter.emit('test', arg1, arg2/*…args*/); // Two above listeners invoked 
emitter.emit('test', arg1, arg2/*…args*/); // Only first listener invoked 

emitter.off('test', listener);              // Removed first listener 
emitter.emit('test', arg1, arg2/*…args*/); // No listeners invoked 

Or a jquery-like deferred library: Deferred

var deferred = require('deferred')

  , count = 0, limit = 10, get;

get = function () {
    var d = deferred();
    setTimeout(function () {
        d.resolve(++count);
    }, 500);
    return d.promise;
};

// Invoke while loop:
get().then(function self(value) {
    console.log(value);
    if (value < limit) return get().then(self);
    return value;
}).done(function () {
    console.log("Done!");

Or with es2015 promises:

var promiseCount = 0;
function testPromise() {
  var thisPromiseCount = ++promiseCount;

  var log = document.getElementById('log');
  log.insertAdjacentHTML('beforeend', thisPromiseCount + 
      ') Started (<small>Sync code started</small>)<br/>');

  // Wir erstellen einen neuen Promise: wir versprechen den String 'result' (Wartezeit max. 3s)
  var p1 = new Promise(
    // Resolver-Funktion kann den Promise sowohl auflösen als auch verwerfen
    // reject the promise
    function(resolve, reject) {       
      log.insertAdjacentHTML('beforeend', thisPromiseCount + 
          ') Promise started (<small>Async code started</small>)<br/>');
      // nur ein Beispiel, wie Asynchronität erstellt werden kann
      window.setTimeout(
        function() {
          // We fulfill the promise !
          resolve(thisPromiseCount)
        }, Math.random() * 2000 + 1000);
    });

  // wir bestimmen, was zu tun ist, wenn der Promise fulfilled
  p1.then(
    // Loggen der Nachricht und des Wertes
    function(val) {
      log.insertAdjacentHTML('beforeend', val +
          ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
    });

  log.insertAdjacentHTML('beforeend', thisPromiseCount + 
      ') Promise made (<small>Sync code terminated</small>)<br/>');
}
vogelino commented 8 years ago

Duplicate of: https://github.com/FH-Potsdam/connecting-bits/issues/22