promise chaining

testing a type of chaining in JavaScript Promises

by Gerald Gillespie

HTML

<div id='main'>
  <ul>

  </ul>
</div>

JavaScript

var lawg = function(val, pretext) {
  if (typeof val === "object") {
    val = val.toString();
  }

  $('#main').find('ul:first')
    .append('<li>' + (pretext || '') + ': ' + val + '</li>');
  console.log((pretext || ''), val);
}; // lawg

//var n = {};

var async = function(t) {
  t = t || 500;
  return new Promise(function(resolve, reject) {
    //always resolve after .5 seconds
    setTimeout(function() {
      resolve('async kept');
    }, t);
  });
}; //aysnc() 


var PFactory = function(name) {

  var n = {};
  if (n[name]) {
    return n[name];
  } else {
    return new function() {

      n[name] = this;
      var _this = this;
      this.promise = Promise.resolve(1);

      this.print = function(all) {
        lawg(all ? n : this);
      };
      // print();
      this.name = function() {

        return name;
      };

      this.doStuff = function(strategy) {
        switch (strategy) {
          case 1:
          case 'chainPromiseReturnPromise': // works well
            return this.promise.then(() => async(500))
              .catch(e => lawg('error in doStuff 1', _this.name()))
              .then(() => lawg('dostuff promise with ' + strategy + ':', _this.name()));
            break;

          case 'chainPromisReturnThis': // not work well
            this.promise.then(() => async(500))
              .catch(e => lawg('error in doStuff 1', _this.name()))
              .then(() => lawg('dostuff promise with ' + strategy + ':', _this.name()));
            return this;
            break;
          case 'resetPromisereturnPromise': // ? 
            return this.promise = this.promise.then(() => async(500))
              .catch(e => lawg('error in doStuff 1', _this.name()))
              .then(() => lawg('dostuff promise with ' + strategy + ':', _this.name()));
            break;
          case 'resetPromiseReturnThis': // works well
          default:
            this.promise = this.promise.then(() => async(500))
              .catch(e => lawg('error...