Ejemplo n.º 1
0
    return this.getLastChunkInfo().bind(this).then(function (lastChunkInfo) {
        var now = Date.now();

        var chunkIds = [];
        var keyFrameIds = [];

        for (var i = 1; i <= lastChunkInfo.chunkId; i++) {
            if (this.chunks[i] !== true) chunkIds.push(i);
        }

        for (var j = 1; j <= lastChunkInfo.keyFrameId; j++) {
            if (this.keyFrames[j] !== true) keyFrameIds.push(j);
        }

        this.chunk_id = i - 1;
        this.keyFrame_id = j - 1;

        var chunkP = Promise.settle(_.map(chunkIds, function (chunkId) {
            return this.getGameDataChunk(chunkId).then(function () {
                this.chunks[chunkId] = true;
            });
        }));

        var keyFrameP = Promise.settle(_.map(keyFrameIds, function (keyFrameId) {
            return this.getKeyFrame(keyFrameId).then(function () {
                this.keyFrames[keyFrameId] = true;
            });
        }));

        // we don't care about the result, just that they're done
        return Promise.settle([chunkP, keyFrameP]); 
    }).then(function () {
Ejemplo n.º 2
0
Importer000.prototype.doUserImport = function (t, tableData, users, errors) {
    var userOps = [],
        imported = [];

    if (tableData.users && tableData.users.length) {
        if (tableData.roles_users && tableData.roles_users.length) {
            tableData = utils.preProcessRolesUsers(tableData);
        }

        // Import users, deduplicating with already present users
        userOps = utils.importUsers(tableData.users, users, t);

        return Promise.settle(userOps).then(function (descriptors) {
            descriptors.forEach(function (d) {
                if (d.isRejected()) {
                    errors = errors.concat(d.reason());
                } else {
                    imported.push(d.value().toJSON());
                }
            });

            // If adding the users fails,
            if (errors.length > 0) {
                t.rollback(errors);
            } else {
                return imported;
            }
        });
    }

    return Promise.resolve({});
};
Ejemplo n.º 3
0
    importPosts: function importPosts(tableData, transaction) {
        if (!tableData) {
            return Promise.resolve();
        }

        var ops = [];

        tableData = stripProperties(['id'], tableData);
        _.each(tableData, function (post) {
             // Validate minimum post fields
            if (areEmpty(post, 'title', 'slug', 'markdown')) {
                return;
            }
             // The post importer has auto-timestamping disabled
            if (!post.created_at) {
                post.created_at = Date.now();
            }

            ops.push(models.Post.add(post, _.extend(internal, {transacting: transaction, importing: true}))
                    .catch(function (error) {
                        return Promise.reject({raw: error, model: 'post', data: post});
                    })
            );
        });

        return Promise.settle(ops);
    },
Ejemplo n.º 4
0
    importTags: function importTags(tableData, transaction) {
        if (!tableData) {
            return Promise.resolve();
        }

        var ops = [];

        tableData = stripProperties(['id'], tableData);
        _.each(tableData, function (tag) {
             // Validate minimum tag fields
            if (areEmpty(tag, 'name', 'slug')) {
                return;
            }

            ops.push(models.Tag.findOne({name: tag.name}, {transacting: transaction}).then(function (_tag) {
                if (!_tag) {
                    return models.Tag.add(tag, _.extend(internal, {transacting: transaction}))
                        .catch(function (error) {
                            return Promise.reject({raw: error, model: 'tag', data: tag});
                        });
                }

                return _tag;
            }));
        });

        return Promise.settle(ops);
    },
Ejemplo n.º 5
0
MilightController.prototype.sendCommands = function (varArgArray) {
    var stackedCommands = [],
        varArgs = arguments,
        self = this;

    return self._lastRequest = Promise.settle([self._lastRequest]).then(function () {

        for (var r = 0; r < self._commandRepeat; r++) {
            for (var i = 0; i < varArgs.length; i++) {
                if (!varArgs[i] instanceof Array) {
                    return Promise.reject(new Error("Array arguments required"));
                }
                else {
                    var arg = varArgs[i];
                    if (((arg.length) > 0) && (arg[0] instanceof Array)) {
                        for (var j = 0; j < arg.length; j++) {
                            stackedCommands.push(self._sendThreeByteArray(arg[j]));
                        }
                    }
                    else {
                        stackedCommands.push(self._sendThreeByteArray(arg));
                    }
                }
            }
        }
        return Promise.settle(stackedCommands)
    });
};
Ejemplo n.º 6
0
    importSettings: function importSettings(tableData, transaction) {
        if (!tableData) {
            return Promise.resolve();
        }

        // for settings we need to update individual settings, and insert any missing ones
        // settings we MUST NOT update are 'core' and 'theme' settings
        // as all of these will cause side effects which don't make sense for an import
        var blackList = ['core', 'theme'],
            ops = [];

        tableData = stripProperties(['id'], tableData);
        tableData = _.filter(tableData, function (data) {
            return blackList.indexOf(data.type) === -1;
        });

        // Clean up legacy plugin setting references
        _.each(tableData, function (datum) {
            datum.key = updatedSettingKeys[datum.key] || datum.key;
        });

        ops.push(models.Settings.edit(tableData, _.extend(internal, {transacting: transaction})).catch(function (error) {
            // Ignore NotFound errors
            if (!(error instanceof errors.NotFoundError)) {
                return Promise.reject({raw: error, model: 'setting', data: tableData});
            }
        }));

        return Promise.settle(ops);
    },
Ejemplo n.º 7
0
	c.on('ready', function () {
		console.log('connected');
		if (grunt.config.get('upload.zips')) {
			promises.push(ftpPromise(c, 'fabrik_build/output/pkg_fabrik_' + version + '.zip',
				'/public_html/media/downloads/pkg_fabrik_' + version + '.zip'));
			promises.push(ftpPromise(c, 'fabrik_build/output/pkg_fabrik_sink_' + version + '.zip',
				'/public_html/media/downloads/pkg_fabrik_sink_' + version + '.zip'));
			promises.push(ftpPromise(c, 'fabrik_build/output/lib_fabrik_' + version + '.zip',
				'/public_html/media/downloads/lib_fabrik_' + version + '.zip'));

			var plugins = fs.readdirSync('fabrik_build/output/pkg_fabrik_sink/packages');

			for (i = 0; i < plugins.length; i++) {
				promises.push(ftpPromise(c, 'fabrik_build/output/pkg_fabrik_sink/packages/' + plugins[i],
					'/public_html/media/downloads/' + plugins[i]));
			}
		}
		if (grunt.config.get('upload.xml')) {
			var xmlFiles = fs.readdirSync('fabrik_build/output/updateserver');

			for (i = 0; i < xmlFiles.length; i++) {
				promises.push(ftpPromise(c, 'fabrik_build/output/updateserver/' + xmlFiles[i],
					'/public_html/update/fabrik31/' + xmlFiles[i]));
			}
		}
		Promise.settle(promises)
			.then(function () {
				c.end();
				done();
			});

	});
Ejemplo n.º 8
0
 function shutdown() {
   log.info('Shutting down all child processes')
   procs.forEach(function(proc) {
     proc.cancel()
   })
   return Promise.settle(procs)
 }
Ejemplo n.º 9
0
		.then(function () {
			console.log('-- Zip promises done');
			console.log('-- Start package build');

			var i, zips = buildConfig.corePackageFiles;
			replace({
				regex: '{version}',
				replacement: version,
				paths: ['./fabrik_build/output/pkg_fabrik/pkg_fabrik.xml',
					'./fabrik_build/output/pkg_fabrik_sink/pkg_fabrik_sink.xml'],
				recursive: false,
				silent: false
			});
			// Copy files from sink to pkg
			for (i = 0; i < zips.length; i++) {
				zips[i] = zips[i].replace('{version}', version);
				try {
					fs.copySync('fabrik_build/output/pkg_fabrik_sink/packages/' + zips[i],
						'fabrik_build/output/pkg_fabrik/packages/' + zips[i]);
				} catch (err) {
					console.error(err.message);
				}

			}
			var promises = [
				zipPlugin('fabrik_build/output/pkg_fabrik_sink', 'fabrik_build/output/pkg_fabrik_sink_' + version + '.zip'),
				zipPlugin('fabrik_build/output/pkg_fabrik', 'fabrik_build/output/pkg_fabrik_' + version + '.zip'),
				zipPlugin('fabrik_build/output/library', 'fabrik_build/output/lib_fabrik_' + version + '.zip')
			];
			Promise.settle(promises)
				.then(function () {
					ftp(grunt, version);
				});

		});
Ejemplo n.º 10
0
  return new Promise( function( resolve ) {
    var options;

    this.grunt.log.verbose.writeln(
      'Executing phantomas ( ' + this.options.numberOfRuns + ' times ) with following parameters:\n' +
      JSON.stringify( this.options.options )
    );

    for ( var i = 0; i < this.options.numberOfRuns; ++i ) {
      options = _.clone( this.options.options );

      // run it only for the first run
      if ( i === 0 && options[ 'film-strip' ] !== false ) {
        options[ 'film-strip' ]     = true;
        options[ 'film-strip-dir' ] = this.imagePath + this.timestamp;
      }

      runs.push(
        phantomas(
          this.options.url,
          options
        )
      );
    }

    Promise.settle( runs )
          .then( resolve )
          .catch( function( e ) {
            console.log( e );
          } );
  }.bind( this ) );
Ejemplo n.º 11
0
		resolver: function(resolve, reject) {
			var _this = this;
			this.resolve = resolve;
			this.reject = reject;

			// get user object.
			this.user = req.userhelper.getUser();

			//push registered networks to `this.networks` array
			this.registerNetworks();

			var promises = [];
			var promise;

			//loop through each network and create promises to get feeds
			this.networks.forEach(function(network){
				//set API Configuration.
				this.networkInstances[network].init(this.getNetworkConfig(network));
				promise = this.getNetworkPromise(this.networkInstances[network].getPromise(), network);
				promises.push(promise);
			}.bind(this));

			Promise
				.settle(promises)
				.then(this.allPromiseCallback.bind(this));
		}
Ejemplo n.º 12
0
MilightController.prototype._createSocket = function () {
    var self = this;

    return Promise.settle([self._socketInit]).then(function () {

        return self._socketInit = new Promise(function (resolve, reject) {
            if (self.clientSocket) {
                return resolve();
            }
            else {
                debug("Initializing Socket");
                var socket = dgram.createSocket('udp4');

                if (self._broadcastMode) {
                    socket.bind(function () {
                        socket.setBroadcast(true);
                        self.clientSocket = socket;
                        debug("Milight: Initializing Socket (broadcast mode) completed");
                        return resolve();
                    });
                }
                else {
                    self.clientSocket = socket;
                    debug("Milight: Initializing Socket done");
                    return resolve();
                }
            }
        });
    });
};
Ejemplo n.º 13
0
function validate (json) {
	var running;
	
	if (!Array.isArray(json)) throw new Error('cache file was corrupted');
	
	running = json.map(function (entry) {
		return Promise.resolve(entry.isPackage).then(function (isPackage) {
			return isPackage ? checkPackage(entry) : checkFile(entry);
		}).then(function (valid) {
			log.debug({module: entry.relName}, 'cached entry was %s, %s', valid ? 'valid' : 'invalid', valid ? 'including' : 'skipping');
			return valid ? entry : Promise.reject();
		});
	});
	
	log.info('checking %d entries from cache file', running.length);
	
	return Promise.settle(running).then(function (results) {
		var ret = results.filter(function (result) {
			return result.isFulfilled();
		}).map(function (result) {
			return result.value();
		});
		
		log.info('keeping %d cached entries from initial %d', ret.length, running.length);
		return ret;
	});
}
Ejemplo n.º 14
0
/* A function that crashes the application */
async function crash (reason_, runHooks_, timeout_) {
    const reason = reason_ || 0;
    const runHooks = (typeof runHooks_ !== 'undefined') ? runHooks_ : true
    const timeout = timeout_ || 5000;

    // NOTE: All hooks are stored as promise-returning functions.  This allows
    // this code to be uniform as hell.

    /* Avoid running hooks multiple times */
    const wasCrashed = G.crashed;
    G.crashed = true;

    /* wait for hooks to complete */
    if (runHooks && !wasCrashed) {
        /* Set the timeout */
        setTimeout(crash.bind(null, EXIT_TIMEOUT, false), timeout).unref();

        /* Get all hook promises */
        const promises = G.hooks.map(fn => fn(reason));
        await Promise.settle(promises);
    }

    /* find out the exit code we should use */
    const exitCode = calcExitCode(reason);
    process.exit(exitCode);
}
Ejemplo n.º 15
0
  return new Promise( function( resolve, reject ) {
    if (
      typeof result.metrics.requests !== 'undefined' &&
      result.metrics.requests.values.length
    ) {
      // keep backwards compatibility
      // to not break existant configurations
      if ( typeof this.options.output === 'string' ) {
        this.options.output = [ this.options.output ];
      }

      // iterate of output formats
      // and write data
      _.each( this.options.output, function( format ) {
        if ( this._writeData[ format ] !== undefined ) {
          runs.push(
            this._writeData[ format ].bind( this )( result )
          );
        } else {
          reject(
            'Your set ouput format \'' + format + '\' is not supported.\n' +
            'PLEASE CHECK DOCUMENTATION FOR SUPPORTED FORMATS.'
          );
        }
      }, this );

      Promise.settle( runs )
          .then( resolve );
    } else {
      reject( 'No run was successful.' );
    }
  }.bind( this ) );
Ejemplo n.º 16
0
function lookup(options) {

  var lookups = [],
      i = 0;

  for(var o = 0; o < options.length; ++o)
  {
    var option = Object.keys(options[o]);

    for(; i < option.length; ++i) {

      if (typeof(options[option]) === 'object') {

        if (options[option].type === 'lookup') {

          lookups.push(this.driver.lookup(options[option])
          .catch(function(err) {

            throw err;
          }));
        }
      }
    }
  }

  return Promise.settle(lookups);
}
Ejemplo n.º 17
0
 return new Promise(function(resolve,reject){
     var promises = []
     slides.forEach(function(slide){
         if(slide.type == 'video'){
             promises.push(s3Signer.getSignedUrl(slide.poster));  
             promises.push(s3Signer.getSignedUrl(slide.src));
         }
         else
             promises.push(s3Signer.getSignedUrl(slide.src));
     });
     Promise.settle(promises).then(function(urls){
         var idx = 0;
         slides.forEach(function(slide){
             if(slide.type == 'video'){
                 slide.poster = urls[idx++].value();
                 slide.src = urls[idx++].value();
             }
             else
                 slide.src = urls[idx++].value();                    
         });            
         resolve(slides);
     }).catch(function(err){
         reject(err);
     });
 })
Ejemplo n.º 18
0
MilightController.prototype._sendThreeByteArray = function (threeByteArray) {
    if (!threeByteArray instanceof Array) {
        return Promise.reject(new Error("Array argument required"));
    }
    var buffer = new Buffer(threeByteArray),
        self = this;

    return self._sendRequest = Promise.settle([self._sendRequest]).then(function () {

        return new Promise(function (resolve, reject) {
            self._createSocket().then(function () {
                self.clientSocket.send(buffer
                    , 0
                    , buffer.length
                    , self.port
                    , self.ip
                    , function (err, bytes) {
                        if (err) {
                            debug("UDP socket error:" + err);
                            return reject(err);
                        }
                        else {
                            debug('Milight: bytesSent=' + bytes + ', buffer=[' + buffer2hex(buffer) + ']');
                            return Promise.delay(self._delayBetweenCommands).then(function () {
                                return resolve();
                            });
                        }
                    }
                );
            }).catch(function (error) {
                return reject(error);
            })
        })
    })
};
Ejemplo n.º 19
0
    ).then(function (filesArr) {
        var files = Array.prototype.concat.apply([], filesArr);

        return Promise.settle(
            files.map(lintFile)
        );
    }, function (err) {
Ejemplo n.º 20
0
function using() {
    var arglen = arguments.length;
    if (arglen < 2) 
        throw new TypeError("At least 2 arguments are required");
    var f = arguments[arglen - 1];
    if (typeof(f) !== 'function')
        throw new TypeError("Last argument must be a function");

    var resources = new Array(arglen - 1);
    for (var k = 0; k < arglen - 1; ++k) {
        resources[k] = toResource(arguments[k]);
    }
    var settled = Promise.settle(resources);
    return settled.then(function(all) { 
        return all.filter(isFulfilled).map(getValue);
    }).then(function(fulfilled) {
        var retval;
        if (resources.length === fulfilled.length) {
            return Promise
            .try(f, fulfilled, this)
            .finally(cleanup(fulfilled))
        }
        return Promise.reject(
            new Promise.RejectionError("Resource allocation failed"))
            .finally(cleanup(fulfilled));
    });

}
Ejemplo n.º 21
0
 .then(function (servers) {
     return Promise.settle(_.map(servers, function(server) {
         return serverClient
             .addPublicIp(server.id, new PublicIpConverter().convert(publicIpConfig))
             .then(setServerIdToJobInfo(server));
     }));
 });
Ejemplo n.º 22
0
      return new Promise(function (resolve, reject) {

        var fetchPromises = [];

        block.resources.forEach(function(url){
          fetchPromises.push(check({
            block: block,
            url: url
          }).then(function (response){

            if (!response.notmodified && options.download_local.fetch_newer) {
              grunt.log.writeln('Remote newer: ' + response);
            } else if (response.notmodified && options.download_local.fetch_newer) {
              grunt.log.writeln('Remote not newer: ' + response.path);
            } else if (response.notmodified && options.download_local) {
              grunt.log.writeln('Exists: ' + response.path);
            } else if (options.download_local) {
              grunt.log.writeln('Fetch non-existing: ' + response);
            }

            return response.path;
          }));

          return fetchPromises;

        });

        // Wait until all the promises are resolved, then settle
        Promise.settle(fetchPromises).then(function(results){
          grunt.log.writeln('Done fetching/checking resources.');
          var errorCount = 0;

          // Log errors when things are not fetched...
          results.forEach(function(result){
            if (!result.isFulfilled()) {
              errorCount+=1;

              grunt.log.warn('Fetch Error in resources for block: \''+block.name+'\', in target \''+target+'\'.');
              try{
                console.log(result.reason());
              }catch(e){
                console.log(e);
              }
            }
          });

          // Count errors and notify user
          if (errorCount === 0) {
            var success_msg = '\''+block.name+'\' files checked-with/fetched-to: \''+block.download_path+'\'';
            grunt.log.ok(success_msg);
            resolve(success_msg);
          } else {
            var error_msg = 'CDN-Switch: Things did not go well for you :\'(';
            grunt.log.warn(error_msg);
            reject(error_msg);
          }
        });

      });
Ejemplo n.º 23
0
    this.fire_event = function (name, data, cb) {
        let promises = [];
        let promisesSync = [];
        let allPromise = [];
        let syncData;
        //Check plugin will run with event
        for (let i in __pluginManager.plugins) {
            let plugin = __pluginManager.plugins[i];
            let active = plugin.active;
            if (active) {
                if (plugin[name]) {
                    //check plugin run with sync data
                    if (plugin.sync) {
                        promisesSync.push(plugin[name]);
                    }
                    else {
                        promises.push(plugin[name](data));
                    }

                }
            }
        }
        if (promisesSync.length > 0) {
            syncData = data;
            allPromise.push(new Promise(function (done, reject) {
                Promise.each(promisesSync, function (task) {
                    task(syncData).then(function (result) {
                        syncData = result;
                    });
                }).finally(function () {
                    done(syncData);
                });
            }));
        }
        if (promises.length > 0) {
            allPromise.push(Promise.settle(promises).then(function (results) {
                let values = [];
                let errors = [];
                results.forEach(function (result) {
                    if (result.isFulfilled()) {
                        values.push(result.value());
                    }
                    else {
                        errors.push(result.reason());
                    }
                });
                return values;
            }));
        }
        if (allPromise.length > 0) {
            Promise.all(allPromise).then(function (results) {
                cb(null, results.join(''));
            });
        }
        else {
            cb(null, '');
        }

    };
Ejemplo n.º 24
0
MilightController.prototype.pause = function (ms) {
    var self = this;
    ms = ms || 100;

    return self._lastRequest = Promise.settle([self._lastRequest]).then(function () {
        return Promise.delay(ms);
    })
};
Ejemplo n.º 25
0
 function addSecondaryNetworksForServers(prop) {
     return Promise.settle(
         _.chain(prop.servers)
         .map(_.partial(addSecondaryNetworks, prop.configs))
         .flatten()
         .value()
     );
 }
Ejemplo n.º 26
0
function createLinks (links, opts) {
	return Promise.settle(links.map(function (entry) {
		if (entry instanceof Promise) return entry;
		return env({cwd: entry.path, force: opts.force}).then(function (opts) {
			return link(opts);
		});
	}));
}
Ejemplo n.º 27
0
 .then(function(servers) {
     return Promise.settle(
         _.map(servers, function(server) {
             return serverClient.revertToSnapshot(server.id, getSnapshotId(server))
                 .then(setServerIdToJobInfo(server));
         })
     );
 });
Ejemplo n.º 28
0
    }).then(function(pkg) {
      var fileTypes = ["js", "json", "html"];

      log.debug("trying to read the different file types");

      return q.settle(fileTypes.map(function(type) {
        return fs.readFileAsync(self.parsed.snippetFolder + "/" + name + "." + type, "utf8");
      })).spread(function(js, json, html) {

        if (!js.isFulfilled()) {
          r.res.writeHead(500);
          return r.res.end("could not find a snippet example");
        }

        pkg.sniper.srcs[name].js = {
          content: js.value(),
        };
        if (html.isFulfilled()) {
          pkg.sniper.srcs[name].html = {
            content: html.value(),
          };
        }
        if (json.isFulfilled()) {
          pkg.sniper.extra = {};
          pkg.sniper.extra[name] = JSON.parse(json.value());
        }

        // to enable github mode
        //html_url: "https://github.com/" + pkg.github.full_name + "/" + pkg.github.default_branch + "/blob/snippets/fer1.js"

        var obj = {
          snippetName: name,
          pkg: pkg,
          services: services
        };

        // TODO: load extra config
        // TODO: load html

        log.debug("send snippet info to the snippet assembler");
        return SnippetDemo(obj).then(function(example) {
          r.res.writeHead(200, {
            'Content-Type': 'text/html'
          });
          r.res.write("<div style='background-color: rgba(240,0,0,0.7); margin-bottom: 10px;'><b>Warning</b>: The local emulation of the BioJS registry is in alpha</div>");
          r.res.write(sniper.renderHead(templates.snip, example));
          r.res.write(example.inlineBody);
          r.res.end("<script>" + example.inlineScript + "</script>");
        }).catch(function(e){
            throw e;
        });
      }).catch(function(e) {
          console.dir(e.details);
          console.dir(e.details.stack);
          r.res.writeHead(500);
          return r.res.end(JSON.stringify(e));
      });
    });
Ejemplo n.º 29
0
function link (opts) {
	var target = opts.target;
	if (!opts.env.hasConfig()) {
		return reject('cannot link in non-project directory, no configuration found (%s)', opts.env.cwd);
	}
	if (Array.isArray(target) || (typeof target == 'string' && target.indexOf(',') > -1)) {
		return Promise.settle((Array.isArray(target) ? target : target.split(',')).map(function (sub) {
			var sopts = {target: sub, force: opts.force, save: opts.save, env: opts.env};
			return link(sopts);
		}));
	}
	return find(opts).then(function (source) {
		return opts.env.get('libDir').then(function (libDir) {
			libDir = libDir ? path.join(opts.env.cwd, libDir) : opts.env.cwd;
			return fs.ensureDirAsync(libDir).then(function () {
				target = path.join(libDir, target);
				return fs.lstatAsync(target).then(function (stat) {
					if (stat.isSymbolicLink()) {
						if (opts.force) {
							return unlink(target).then(function () {
								return symlink(source, target);
							});
						} else {
							return reject('%s is already a symbolic link, use the --force flag to recreate the link', target);
						}
					} else if (stat.isDirectory()) {
						if (opts.force) {
							return fs.removeAsync(target).then(function () {
								return symlink(source, target);
							});
						} else {
							return reject('%s is a directory, use the --force flag to overwrite the directory with the link', target);
						}
					} else {
						if (opts.force) {
							return fs.unlink(target).then(function () {
								return symlink(source, target);
							}, function (e) {
								return reject('could not overwrite the existing file at %s: %s', target, e.message);
							});
						} else {
							return reject('%s is a file, use the --force flag to overwrite the file with the link', target);
						}
					}
				}, function () {
					return symlink(source, target).then(function () {
						if (opts.save) {
							return opts.env.config.set('links', opts.target, true);
						}
					});
				});
			}, function (e) {
				return reject('could not create "libDir" (%s): %s', libDir, e.message);
			});
		});
	});
}
Ejemplo n.º 30
0
 removeAll: function () {
   var toBeRemoved = [];
   db.findAsync({}).then(function (terminals) {
     terminals.forEach(function (terminal) {
       toBeRemoved.push(removeTerminal(terminal.terminal_id));
     });
   });
   return Promise.settle(toBeRemoved);
 },