How to use the async.forEachOf function in async

To help you get started, we’ve selected a few async examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mediocre / mehdown / lib / index.js View on Github external
if (!commandMatches || !commandMatches.length) {
                return callback();
            }

            var commandIndex = 0;

            var lines = markdown.split(/\n/gmi).map(l => {
                var isCommand = new RegExp(exports.commandRegExp.source, 'gim').test(l);

                return {
                    commandIndex: isCommand ? commandIndex++ : -1,
                    markdown: l
                };
            });

            async.forEachOf(commandMatches, function(commandMatch, index, callback) {
                var tokens = new RegExp(exports.commandRegExp.source, 'gim').exec(commandMatch);

                // The command's name is captured in the first match.
                var commandName = tokens[1];
                var command = commands[commandName.toLowerCase()];

                // If the /command isn't supported, return.
                if (!command) {
                    return callback();
                }

                // Get the command's arguments.
                var args = tokens[2];

                // Execute the /command
                command(args, (err, result) => {
github bids-standard / bids-validator / validate.js View on Github external
function BIDS (fileList, callback) {
    var errors = [];
    async.forEachOf(fileList, function (file, key, cb) {

        // validate tsv
        if (file.name && file.name.indexOf('.tsv') > -1) {
        	utils.readFile(file, function () {
        		validate.TSV(file, function () {
	                cb();
	            });
        	});
            return;
        }

        // validate json
        if (file.name && file.name.indexOf('.json') > -1) {
            utils.readFile(file, function (contents) {
                validate.JSON(contents, function (err) {
                    if (err) {
github adblockradio / adblockradio / predictor-db / findDataFiles.js View on Github external
async.forEachOf(radioDirs, function(radioDir, index, radioDirCallback) {
					async.forEachOf(consts.WLARRAY, function(dataDir, index, dataDirCallback) {
						var path = options.path + "/records/" + dateDir + "/" + radioDir + "/" + dataDir;
						fs.stat(path, function(err, stat) {
							if (stat && stat.isDirectory()) {
								getFiles(path, timeFrame.after, timeFrame.before, function(partialFiles) {
									log.debug("findDataFiles: " + dataDir + ": " + Object.keys(partialFiles).length + " files found");
									Object.assign(files[dataDir], partialFiles); // = files[dataDir].concat(fullPathFiles);
									dataDirCallback();
								});
							} else {
								dataDirCallback();
							}
						});

					}, function(err) {
						if (err) log.error("findDataFiles: pb during data dir listing. err=" + err.message);
						radioDirCallback();
github AugurProject / augur / packages / augur-tools / scripts / dp / lib / cancel-orders.js View on Github external
augur.trading.getOrders({ creator: creator, universe: universe, orderState: augur.constants.ORDER_STATE.OPEN }, function (err, orders) {
    if (err) return callback(err);
    async.forEachOf(orders, function (ordersInMarket, marketId, nextMarket) {
      async.forEachOf(ordersInMarket, function (ordersInOutcome, outcome, nextOutcome) {
        async.forEachOf(ordersInOutcome, function (buyOrSellOrders, orderType, nextOrderType) {
          async.each(Object.keys(buyOrSellOrders), function (orderId, nextOrder) {
            if (debugOptions.cannedMarkets) console.log(chalk.green(orderId), chalk.red.bold(orderType), JSON.stringify(buyOrSellOrders[orderId], null, 2));
            cancelOrder(augur, orderId, orderType, marketId, parseInt(outcome, 10), auth, nextOrder);
          }, nextOrderType);
        }, nextOutcome);
      }, nextMarket);
    }, callback);
  });
}
github Rostlab / JS16_ProjectA / app / controllers / filler / characters.js View on Github external
if(policy === 1) {
            CharacterPlod.remove({}, function(err) {
                console.log('CharacterPlods cleared.');
                async.forEachOf(plods,function(plod, char, cb){
                    addNewPlod(char,plod,function() {
                        cb();
                    });
                }, function(err) {
                    module.exports.updateArffPlods(policy,callback);
                });
            });
        }
        else {
            var slug;
            async.forEachOf(plods,function(plod, char, cb){
                slug = char.replace(/'/g,'_').replace(/ /g,'_');
                CharacterPlod.findOne({'characterSlug':slug,'algorithm':'gotplod'}, function (err, oldChar) {

                    if (err || oldChar === null || oldChar === undefined) {
                        console.log(char + ' is new!');
                        addNewPlod(char,plod,function() {
                            cb();
                        });
                    } else {
                        if(policy == 2 || (policy == 3 && oldChar.plod === undefined)) {
                            oldChar.plod = plod;
                            oldChar.date = new Date();
                            oldChar.save(function(err){
                                console.log('gotplod:' + oldChar.character + ' got updated by the plod ' + plod);
                                if(err){
                                    console.log('gotplod:' + 'Error updating character: ' + err);
github theRoughCode / WatsMyMajor / server / core / update.js View on Github external
async function updateClass(subject, catalogNumber, term) {
  const { err, classInfo } = await classScraper.getClassInfo(subject, catalogNumber, term);
  if (err) return err;

  try {
    await classesDB.setClasses(subject, catalogNumber, term, classInfo);
    asyncjs.forEachOf(classInfo, (info, _, callback) => {
      info.subject = subject;
      info.catalogNumber = catalogNumber;
      updateWatchlist(term, info);
    }, err => {
      if (err) return err;
      else return null;
    });
  } catch (err) {
    return err;
  }
}
github AugurProject / augur.js / src / events / start-blockchain-event-listeners.js View on Github external
function setupBlockstream(eventCallbacks, onSetupComplete) {
  var blockStream = ethrpc.getBlockStream();
  if (!blockStream) return onSetupComplete(new Error("Not connected to Ethereum"));
  if (!isObject(eventCallbacks)) return onSetupComplete(new Error("No event callbacks found"));
  var eventsAbi = contracts.abi.events;
  var activeContracts = contracts.addresses[ethrpc.getNetworkID()];
  blockStream.subscribeToOnLogAdded(subscriptions.onLogAdded);
  blockStream.subscribeToOnLogRemoved(subscriptions.onLogRemoved);
  async.forEachOf(eventCallbacks, function (callbacks, contractName, nextContract) {
    async.forEachOf(callbacks, function (callback, eventName, nextEvent) {
      if (!isFunction(callback) || !eventsAbi[contractName] || !eventsAbi[contractName][eventName]) {
        return nextEvent(new Error("ABI not found for event " + eventName + " on contract " + contractName));
      }
      if (!addFilter(blockStream, contractName, eventName, eventsAbi[contractName][eventName], activeContracts, subscriptions.addSubscription, callback)) {
        return nextEvent(new Error("Event subscription setup failed: " + contractName + " " + eventName));
      }
      nextEvent(null);
    }, nextContract);
  }, function (err) {
    if (err) return onSetupComplete(err);
    onSetupComplete(null);
  });
}
github taskrabbit / elasticsearch-dump / lib / transports / elasticsearch.js View on Github external
setAliases (data, limit, offset, callback) {
    if (this.haveSetAliases === true || data.length === 0) {
      return callback(null, 0)
    }

    try {
      data = jsonParser.parse(data[0])
    } catch (e) {
      return callback(e)
    }

    const payload = {
      actions: []
    }

    async.forEachOf(data, async.ensureAsync((_data, index, cb) => {
      if (!_.has(_data, 'aliases') || _.isEmpty(_data.aliases)) {
        return cb(new Error('no aliases detected'))
      }

      async.forEachOf(_data.aliases, async.ensureAsync((aliasOptions, alias, acb) => {
        payload.actions.push({ add: Object.assign({ index, alias }, aliasOptions) })
        return acb()
      }), () => {
        return cb()
      })
    }), err => {
      if (err) { return callback(err) }
      this.haveSetAliases = true

      const esRequest = {
        url: `${this.base.host}/_aliases`,
github AugurProject / augur-node / src / blockchain / log-processors / order-filled / upsert-position-in-market.ts View on Github external
db.select("outcome").from("positions").where({ account, marketId }).asCallback((err: Error|null, positionsRows?: Array>): void => {
    if (err) return callback(err);
    const numOutcomes = positionInMarket.length;
    const realizedProfitLoss = new Array(numOutcomes);
    const unrealizedProfitLoss = new Array(numOutcomes);
    const positionInMarketAdjustedForUserIntention = new Array(numOutcomes);
    const averagePrice = new Array(numOutcomes);
    forEachOf(positionInMarket, (numShares: string, outcome: number, nextOutcome: AsyncCallback): void => {
      augur.api.Orders.getLastOutcomePrice({ _market: marketId, _outcome: outcome }, (err: Error|null, lastOutcomePrice: Int256): void => {
        if (err) return callback(err);
        const lastPrice = new BigNumber(lastOutcomePrice, 10);
        const price = augur.utils.convertOnChainPriceToDisplayPrice(lastPrice, minPrice, tickSize).toFixed();
        db("outcomes").where({ marketId, outcome }).update({ price }).asCallback((err: Error|null): void => {
          if (err) return callback(err);
          calculateProfitLossInOutcome(db, augur, account, marketId, outcome, (err: Error|null, profitLossInOutcome?: CalculatedProfitLoss): void => {
            if (err) return nextOutcome(err);
            const { realized, unrealized, position, meanOpenPrice } = profitLossInOutcome!;
            realizedProfitLoss[outcome] = realized;
            unrealizedProfitLoss[outcome] = unrealized;
            positionInMarketAdjustedForUserIntention[outcome] = position;
            averagePrice[outcome] = meanOpenPrice;
            nextOutcome(null);
          });
        });
github itgalaxy / favicons / helpers-es5.js View on Github external
async.each(tags, function (platform, callback) {
                async.forEachOf(platform, function (tag, selector, cb) {
                    if (options.replace) {
                        $(selector).remove();
                    } else if ($(selector).length) {
                        newCode(selector).remove();
                    }
                    return cb(null);
                }, callback);
            }, function (error) {
                target.append(newCode.html());