本文整理汇总了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());
}
}
}
示例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);
});
示例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);
}
示例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);
}
示例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);
}
示例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)
})
}
示例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);
}
示例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('/');
})
}
});
示例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]);
});
});
});
});
示例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);
}
示例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});
});
}
示例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);
}
示例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()
});
}
示例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]);
}
);
},
示例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);
});
}
});