mozilla / node-firefox

node.js modules for interacting with Firefox via the DevTools remote protocol
https://www.npmjs.org/package/firefox
Mozilla Public License 2.0
301 stars 18 forks source link

Examples should use chained promises to simplify callback pyramids #26

Open lmorchard opened 9 years ago

lmorchard commented 9 years ago

Promises can be chained, rather than nested like callbacks. That makes code much cleaner. Here's a quick sample of dirty code I'm using to exercise modules:

var path = require('path');
var fs = require('fs');

var Promise = require('es6-Promise').Promise;

var startSimulator = require('./node-firefox-start-simulator');
var connect = require('./node-firefox-connect');
var installApp = require('./node-firefox-install-app');
var findApp = require('./node-firefox-find-app');
var launchApp = require('./node-firefox-launch-app');
var uninstallApp = require('./node-firefox-uninstall-app');

var appPath = path.join(__dirname, 'node-firefox-install-app/examples/sampleApp');
var manifest = JSON.parse(fs.readFileSync(appPath + '/manifest.webapp'));

var client, simulator, appId, installedApp;

startSimulator().then(function(result) {
  simulator = result;
  return connect(simulator.port);
}).then(function(result) {
  client = result;
  return installApp({ client: client, appPath: appPath });
}).then(function(result) {
  appId = result;
  return findApp({ client: client, manifest: manifest });
}).then(function(apps) {
  installedApp = apps.filter(function (app) { return app.id == appId; })[0];
  if (!installedApp) { throw new Error('Installed app not found!'); }
  return launchApp({ client: client, manifestURL: installedApp.manifestURL });
}).then(function(result) {
  return delay(3000);
}).then(function() {
  return uninstallApp({ client: client, manifestURL: installedApp.manifestURL });
}).then(function() {
  client.disconnect();
  process.kill(simulator.pid);
  process.exit();
}).catch(function(err) {
  console.error('Error', err);
  process.exit();
});

function delay(ms) {
  return new Promise(function (resolve, reject) {
    setTimeout(resolve, ms);
  });
}

I'll probably work through the various libraries and submit PRs myself. But, here's an issue filed just in case I don't get around to it.

tofumatt commented 9 years ago

Yes, this is awesome and our examples should encourage this usage. The localForage tests look SOOOO much nicer with this style of promises. +1!

sole commented 9 years ago

Yes, also see https://github.com/mozilla/node-firefox/issues/20 which is related