Chaining Dynamic Promises

by amindunited

JavaScript

const timedPromise = (delay, result = '') => {
  const promise = new Promise((resolve) => {
    setTimeout(() => {
      console.log('timedPromise Resolving')
      resolve(result);
    }, delay);
  });
  return promise;
};

const customFunctions = {
	mkdir: async function () {
		const actions = await timedPromise(1000, 'made dir');
    return actions;
  },
	copyFile: async function () {
		const actions = await timedPromise(1000, 'copied');
    return actions;
  },
	openFile: async function () {
		const actions = await timedPromise(1000, `{ json: "1.0", created: "1972"}`);
    return actions;
  },
  editJson: async function () {
  	const contents = await (await Creator()).openFile().last();
    console.log('edit json', contents);
    
    return contents;
  }
};


const Creator = async function () {
	const $ = {
  	promises: Promise.resolve(),
  	chain: [],
    close: async function () {
    	console.log('closing on', $);
    	const ch = await Promise.all($.chain);
      return ch;
    },
    last: async function () {
    	const ch = await Promise.all($.chain);
      return ch.pop();
    }
  };
  
  
    
  // This would be the loading of FNs
  await Promise.resolve();
  
  Object.keys(customFunctions).forEach((key) => {
  	$[key] = function (...args) {
      $.chain.push(customFunctions[key](...args));
      return $;
    }
  });
  
  
  return $;
  
};


(async () => {
	const creator = await Creator().then((c) => { console.log('double then'); return c; });
  const chain = await creator.mkdir().copyFile().close();
  console.log('creator instance', chain);
  
  const editing = await (await Creator()).mkdir().copyFile().editJson().close();
  console.log('editing', editing);  
})();