当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript async.waterfall函数代码示例

本文整理汇总了TypeScript中async.waterfall函数的典型用法代码示例。如果您正苦于以下问题:TypeScript waterfall函数的具体用法?TypeScript waterfall怎么用?TypeScript waterfall使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了waterfall函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: if

    (res, callback) => {
        // In order to call the callback after we are done, we have to use a counter
        var counter = res.length;
        var markOneAsProcessed = () => { if (--counter == 0) callback(); };

        // For each person
        for (var i = 0; i < res.length; i++) {
            var p = res[i];

            // If Person is customer
            if (p.isCustomer) {
                async.waterfall([
                    // Read customer details for person
                    callback => database.collection("Customer", callback),
                    (custColl, callback) => custColl.findOne({ id: p.customerId }, callback),

                    // Print person and customer details
                    (cust, callback) => { console.log(`John ${cust.lastName} works for ${cust.customerName}.`); callback(); },
                ], (err, result) => markOneAsProcessed());
            } else {
                async.waterfall([
                    // Read supplier details for person
                    callback => database.collection("Supplier", callback),
                    (supplColl, callback) => supplColl.findOne({ id: p.supplierId }, callback),

                    // Print person and supplier details
                    (suppl, callback) => { console.log(`John ${suppl.lastName} works for ${suppl.customerName}.`); callback(); },
                ], (err, result) => markOneAsProcessed());
            }
        }
    }
开发者ID:HansenHo,项目名称:Samples,代码行数:31,代码来源:app.ts

示例2: callback

			fs.exists(dir, (exists:bool) => {
				if (!exists) return callback('path does not exists: ' + dir, null);

				async.waterfall([
					(callback:AsyncCallback) => {
						return fs.stat(dir, callback);
					},
					(stats, callback:AsyncCallback) => {
						if (!stats.isDirectory()) {
							return callback('path is not a directory: ' + dir, null);
						}
						return fs.readdir(dir, callback);
					},
					(files:string[], callback:AsyncCallback) => {
						//check each file
						async.forEach(files, (file:string, callback:AsyncCallback) => {
							var full = path.join(dir, file);
							fs.stat(full, (err, stats)=> {
								if (err) return callback(err, null);
								if (stats.isFile()) {
									return fs.unlink(full, callback);
								}
								return callback(null, null);
							})
						}, callback);
					}
				], callback);
			});
开发者ID:Bartvds,项目名称:tsd-deftools,代码行数:28,代码来源:helper.ts

示例3: gatherFicInfos

    gatherFicInfos(completedCallback: AsyncResultCallback<any, any>) : void
    {
        var self = this;
        Async.waterfall([
            function (callback: typedef.Callback) 
            {
                var id = self.findId();
                if (!id)
                    return callback("Couldn't find fic ID.");

                callback(null);
            },
            function (callback: typedef.Callback) 
            {
                self.getPageSourceCode(0, callback);
            },
            function (body: string, callback: typedef.Callback) 
            {
                if (self.isValidFic(body)) 
                {
                    var infos = self.findFicInfos(body);
                    callback(null)
                }
                else
                    callback("Invalid fic URL.");
            }
        ], completedCallback);
    }
开发者ID:p0ody,项目名称:ff2ebook-node,代码行数:28,代码来源:FicFFNET.ts

示例4: proveAndSend

function proveAndSend(program:any, server:Server, block:any, issuer:any, difficulty:any, done:any) {
  const logger = server.logger;
  async.waterfall([
    function (next:any) {
      block.issuer = issuer;
      program.show && console.log(block.getRawSigned());
      (async () => {
        try {
          const host:string = program.submitHost
          const port:string = program.submitPort
          const trialLevel = isNaN(difficulty) ? await server.getBcContext().getIssuerPersonalizedDifficulty(server.PeeringService.selfPubkey) : difficulty
          const prover = new BlockProver(server);
          const proven = await prover.prove(block, trialLevel);
          if (program.submitLocal) {
            await server.writeBlock(proven)
            next()
          } else {
            const peer = PeerDTO.fromJSONObject({
              endpoints: [['BASIC_MERKLED_API', host, port].join(' ')]
            });
            program.show && console.log(proven.getRawSigned());
            logger.info('Posted block ' + proven.getRawSigned());
            const p = PeerDTO.fromJSONObject(peer);
            const contact = new Contacter(p.getHostPreferDNS(), p.getPort());
            await contact.postBlock(proven.getRawSigned());
            next()
          }
        } catch(e) {
          next(e);
        }
      })()
    }
  ], done);
}
开发者ID:Kalmac,项目名称:duniter,代码行数:34,代码来源:index.ts

示例5: breakupFile

    breakupFile(filepath, final_callback) {
        async.waterfall([
            (callback) => {
                let command = OS_BATCH_RUN_PREFIX + ' pdftk ' + filepath + ' dump_data';
                logging.info('Running external command: ' + command);
                child_process.exec(command, function (err, stdout, stderr) {
                    if (err || !stdout)
                        return callback(err || stderr);
                    let pageCount = parseInt(/NumberOfPages: (\d+)/.exec(stdout)[1]);
                    if (!pageCount) return callback('Error reading number of pages');
                    callback(null, pageCount);
                });
            },
            (pageCount, callback) => {
                let output = BURST_FOLDER + duid.getDUID(1)[0] + '_page_%02d.pdf';
                mkdirp.sync(BURST_FOLDER); //this folder is periodically removed

                let command = OS_BATCH_RUN_PREFIX + ' pdftk ' + filepath + ' burst output ' + output;
                logging.info('Running external command: ' + command);
                child_process.exec(command, (err, stdout, stderr)=> {
                    if (err)
                        return callback(err || stderr);

                    let files = [];
                    let i = 1;
                    while (i <= pageCount) {
                        let no = ('0' + (i++).toString()).slice(-2);
                        files.push(output.replace('%02d', no));
                    }
                    callback(null, files);
                });
            }], final_callback);
    }
开发者ID:zaksie,项目名称:gotouch,代码行数:33,代码来源:pdf.ts

示例6: compileAndDeploy

function compileAndDeploy(filename: string, callback: Function) {
  let web3: Web3 = new Web3()
  web3.setProvider(new Provider())
  let compilationData: object
  let accounts: string[]
  async.waterfall([
    function getAccountList(next: Function): void {
      web3.eth.getAccounts((_err: Error | null | undefined, _accounts: string[]) => {
        accounts = _accounts
        next(_err)
      })
    },
    function compile(next: Function): void {
      compileFileOrFiles(filename, false, { accounts }, next)
    },
    function deployAllContracts(compilationResult: object, next: Function): void {
      try {
        compilationData = compilationResult
        deployAll(compilationResult, web3, next)
      } catch (e) {
        throw e
      }
    }
  ], function (_err: Error | null | undefined, contracts: any): void {
    callback(null, compilationData, contracts, accounts)
  })
}
开发者ID:0mkara,项目名称:remix,代码行数:27,代码来源:testRunner.ts

示例7: openRecentOrderAux2

 private openRecentOrderAux2(final_callback, tx, cookie, orders) {
     var data = new Object as any;
     async.waterfall([
         (callback) => {
             let result = _.last(orders);
             result = result.entity;
             data.placeid = result.key.path[1].name;
             data.tab = Util.fromProtoEntity(result.properties);
             app.business.find(data.placeid, {}, callback, tx);
         },
         (business, callback) => {
             data.business = business;
             app.orderArticle.fetchByCookieId(cookie, data.placeid, callback, tx);
         },
         (result, queryinfo, callback) => {
             this.fetchAllOrderArticles(result, data, callback);
         },
         (results, callback) => {
             this.populateArticlesOrRemoveIfEmpty(cookie, results, data, (err, result) => {
                 if (!err && !result)
                     this.openRecentOrderAux2(callback, tx, cookie, orders);
                 else
                     callback(err, result);
             });
         }
     ], final_callback);
 }
开发者ID:zaksie,项目名称:gotouch,代码行数:27,代码来源:order.ts

示例8: function

     .exec((err, user) => {
     if (err) return next(err);
     if (!user) return next({ message: 'Invalid user' });
     if (user) {
         async.waterfall([
             function(cb) {
                 crypto.randomBytes(5, (err, buf) => {
                     let token = buf.toString('hex');
                     cb(err, token);
                 });
             }, function(token, cb) {
                 user.resetPasswordToken = token;
                 user.resetPasswordDate = Date.now() + 3600000;
                 user.save((err) => {
                   if(err) return next(err);
                     cb(err, token, user);
                 });
             }, function(token, user: app.i.IUser, cb) {
                 let mailOptions = {
                     from: 'Folio Team <folioteamcc@gmail.com>',
                     to: user.email,
                     subject: 'Folio Password Reset',
                     html: 'Hey ' + user.name + ',<br><br>' + 'We heard you forgot your password.<br><br>' + 'Click on the link below to reset<br>' + 'https://ccfolio.herokuapp.com/resetPassword/' + token + '<br><br>' + 'If you did not request a reset, please ignore this email. Your password will not be reset.<br><br>' + 'Have a great day!<br><br>' + 'xo,<br>' + 'The Folio Team'
                 };
                 transporter.sendMail(mailOptions, (err) => {
                   if(err) return next(err);
                     return res.redirect('/');
                 })
             }], function(err) {
                 if (err) return next(err);
                 return res.redirect('/');
             })
     }
 });
开发者ID:Jeremy-Doucet,项目名称:March-7-Group-Project,代码行数:34,代码来源:controller.ts

示例9: waterfall

            return new Promise<any>((resolve: Function, reject: Function) => {

                // start the pre and then run the rest of the wrapped
                waterfall([constant.apply(undefined, args)].concat(f.stack.pre), (err: Error, ...args: Array<any>) => {

                    // if error is made
                    if (err) {
                        return reject(err);
                    }

                    // apply the new arguments and get actor results
                    applyEach(f.stack.actor, args, (err: Error, result: Array<any>) => {

                        // if error is made
                        if (err) {
                            return reject(err);
                        }

                        // push result into args
                        args.push(result);

                        // start the post hooks and return values
                        waterfall([constant.apply(undefined, args)].concat(f.stack.post), (err: Error, ...results: Array<any>) => {

                            // if error is made
                            if (err) {
                                return reject(err);
                            }

                            // return the actual result as the last elemnt of the array
                            resolve(results[results.length - 1]);
                        });
                    });
                });
            });
开发者ID:MedSolve,项目名称:make-it-hookable,代码行数:35,代码来源:hook.component.ts

示例10: kongPostApi

export function kongPostApi(apiConfig: KongApi, callback: Callback<KongApi>): void {
    debug('kongPostApi()');
    const { service, route } = wicked.kongApiToServiceRoute(apiConfig);
    let persistedService: KongService = null;
    let persistedRoute: KongRoute = null;
    async.waterfall([
        callback => kongPostService(service, callback),
        (s: KongService, callback) => {
            persistedService = s;
            route.service = {
                id: s.id
            }
            kongPostRoute(route, callback);
        },
        (r: KongRoute, callback) => {
            persistedRoute = r;
            return callback(null);
        }
    ], (err) => {
        if (err)
            return callback(err);
        return callback(null, wicked.kongServiceRouteToApi(persistedService, persistedRoute));
    })
    //kongPost('apis', apiConfig, callback);
}
开发者ID:Haufe-Lexware,项目名称:wicked.portal-kong-adapter,代码行数:25,代码来源:utils.ts

示例11: download

export function download(params:any, userIdKey: string, callback: type.Callback) {
    function validate(params:any) {
        var checks = [];
        if (!params) checks.push('Parameter is required.');
        if (params && !params.fileId) checks.push('FileID is required.');
        if (checks.length > 0) {
            callback.onFailure(new error.InvalidParamsError(checks, null));
            return false;
        }
        return true;
    }
    if (!validate(params)) return;

    var con = new db.Database();

    var caseDAO = new model_assurance_case.AssuranceCaseDAO(con);
    async.waterfall([
        (next) => {
            caseDAO.get(params.fileId, (err: any, acase: model_assurance_case.AssuranceCase) => next(err, acase));
        }],
        (err:any, result: model_assurance_case.AssuranceCase) => {
            con.close();
            if (err) {
                callback.onFailure(err);
                return;
            }
        callback.onSuccess({content: result.data});
    });

}
开发者ID:AssureNote,项目名称:AssureNote,代码行数:30,代码来源:assurance_case.ts

示例12: function

 pow: function (conf:ConfDTO, done:any) {
   async.waterfall([
     function (next:any){
       simpleInteger("Start computation of a new block if none received since (seconds)", "powDelay", conf, next);
     }
   ], done);
 }
开发者ID:duniter,项目名称:duniter,代码行数:7,代码来源:wizard.ts

示例13: function

        function (req: restify.Request, res: restify.Response, next: restify.Next) {
            if (!isShallowSubset(req.body, user_schema.properties))
                return res.json(400, {
                        error: 'ValidationError',
                        error_message: 'Invalid keys detected in body'
                    }) && next();
            else if (!req.body || !Object.keys(req.body).length)
                return res.json(400, {error: 'ValidationError', error_message: 'Body required'}) && next();

            const User: waterline.Query = collections['user_tbl'];

            async.waterfall([
                cb => User.findOne({email: req['user_id']},
                    (err: waterline.WLError, user: IUser) => {
                        if (err) cb(err);
                        else if (!user) cb(new NotFoundError('User'));
                        return cb(err, user)
                    }),
                (user, cb) =>
                    User.update(user, req.body, (e, r: IUser) => cb(e, r[0]))
            ], (error, result) => {
                if (error) return next(fmtError(error));
                res.json(200, result);
                return next()
            });
        }
开发者ID:healthplatform,项目名称:rest-api,代码行数:26,代码来源:routes.ts

示例14: next

 (recipient, next) => {
   async.waterfall(
     [
       (next) => {
         this._getDataForTemplate(notification, recipient, next);
       },
       (data, next) => {
         async.map(
           ['plain', 'html'],
           (type, next) => {
             this._loadTemplate(emailType, recipient, '.' + type, (
               err,
               template
             ) => {
               if (err && type == 'html') return next();
               if (err) return next(err);
               this._applyTemplate(template, data, (err, res) => {
                 return next(err, [type, res]);
               });
             });
           },
           (err, res: any) => {
             return next(err, _.fromPairs(res.filter(Boolean)));
           }
         );
       },
       (result, next) => {
         next(null, result);
       }
     ],
     (err, res) => {
       next(err, [recipient.language, res]);
     }
   );
 },
开发者ID:bitpay,项目名称:bitcore,代码行数:35,代码来源:emailservice.ts

示例15: normalizeModelToOpen

  fs.readFile(fileName, 'utf-8', (err, data) => {
    if (err) {
      dialog.showErrorBox('File reading error', err.message);
      return;
    }

    const config = JSON.parse(data);
    const brokenFileActions = [];

    if (config.length) {
      config.forEach(configItem => {
        normalizeModelToOpen(configItem.model, currentDir, brokenFileActions);
      });

      async.waterfall(brokenFileActions, () => {
        const newConfig = getConfigWithoutAbandonedData(config);

        if (!_.isEmpty(newConfig)) {
          sender.send('do-open-all-completed', newConfig);
        }

        setTimeout(() => {
          sender.send('check-tab-by-default');
        }, 500);
      });
    }

    if (!config.length) {
      normalizeModelToOpen(config, currentDir, brokenFileActions);

      async.waterfall(brokenFileActions, () => {
        const newConfigAsArray = getConfigWithoutAbandonedData(config);

        if (!_.isEmpty(newConfigAsArray)) {
          const newConfig = _.head(newConfigAsArray);

          if (!_.isEmpty(newConfig)) {
            sender.send('do-open-completed', {tab: newConfig, file: fileNameOnly});
          }
        }

        setTimeout(() => {
          sender.send('check-tab-by-default');
        }, 500);
      });
    }
  });
开发者ID:VS-work,项目名称:gapminder-offline,代码行数:47,代码来源:file-management.ts


注:本文中的async.waterfall函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。