Node.js-承诺和锥形语句(if、switch等)-如何构建
Node.js - promises and conidtional statements (if, switch, etc) - how to structure?
您能推荐如何正确处理带有许多if/switch和promise的控制流吗?我在网上找到的所有教程都倾向于处理简单的控制流,没有许多(任何?)不同的处理分支。有什么建议阅读或至少搜索词吗?
我现在的做法是将if/switch逻辑封装在一个函数中,该函数在评估条件后返回Promise并返回到主流程循环。有什么办法做得更好、更好吗?
样本代码:
// Check if argument is a valid URL
Promise.promisify(checkUrl)().then(() => {
// Delete all query parameters from URL if present
return sanitizer.cleanAsync(argv.url)
}).then(_cleanUrl => {
cleanUrl = _cleanUrl;
logger.warn(`URL: ${cleanUrl}`);
// Validate Google Analytics view id supplied as '--gaId=<id>' command line argument or exit if it is not present
return Promise.promisify(checkGaId)()
}).then(() => {
// Check if DB exists, if not create it
return db.checkIfDatabaseExistsAsync()
}).then(() => {
// Check if all tables exist, if not create them
return db.checkTablesAsync()
}).then(() => {
// Check DB integrity (possiblDelete all query parameters from URL if presente to turn off in the config)
if (config.database.checkIntegrity) {
return db.integrityChecksAsync();
}
}).then(() => {
// Check if URL already exists in DB, if not insert it
return db.getOrCreateEntryUrlIdAsync(cleanUrl)
}).then(_entryId => {
entryId = _entryId;
// Check if any previous executions for the entry point exist and if so whether the last one completed
return db.getLastExecutionDataAsync(entryId);
}).then(lastExecution => {
// If last execution was not completed prompt for user action
return processLastExecution(entryId, lastExecution)
}).then(_pages => {
... more code follows here...
和processLasExecution
函数的伪代码:
function processLastExecution(entryId, lastExecution) {
return new Promise(
function (resolve, reject) {
// No previous executions found or all was okay
if (lastExecution == null || (lastExecution != null && lastExecution.is_completed == 'Y')) {
...resolves with A;
} else {
Promise.promisify(selectRunOption)().then(option => {
switch (option) {
case 'resume':
...resolves with B;
break;
case 'ignore':
...resolves with C;
break;
case 'delete':
...resolves with D;
break;
default:
...rejects
}
});
}
}
)
}
有什么方法可以更好/更清楚地封装或提供if/switch逻辑?
哦,如果有人想知道这是一个命令行脚本,而不是一个web应用程序,这也不是Node.js的初衷。
我认为最好使用生成器,然后可以编写类似同步的代码:
co(function* () {
// Check if argument is a valid URL
if (yield checkUrl) {
var cleanUrl = yield sanitizer.cleanAsync(argv.url);
...
}
...
}, ...
co可以与callback和promise合作,请参阅https://github.com/tj/co
相关文章:
- 我应该如何从xml文件构建一个javascript页面
- 如何在DOM元素上按类型构建此函数
- Sencha Touch构建-排除文件
- RubyonRails——构建交互式接口应该朝哪个方向发展
- 如何在构建node-webkit应用程序后获取外部资源
- Ext.js从json构建模型关系的问题
- 如何为生产构建angular2应用程序
- Grunt构建导致Angular应用程序在dist上崩溃
- 构建JS测试,警报窗口重复上一个Q,而不是问下一个Q
- 动态构建一个数据表与scriplets
- 如何只使用特定的表行构建简单的手风琴
- 为tweet构建chrome扩展
- 如何构建angular.js应用程序
- 如何使用Meteorjs构建实时应用程序
- jquery从2个json字符串构建一个复选框表单
- webpack开发模式和生产构建模式之间有什么区别
- js文件是否阻碍了war文件的构建
- 如何在Javascript中从select标记的一系列选项中构建二维数组
- 如何使用angularjs构建交互式滚动着陆页
- 西兰花构建dist -构建失败