【发布时间】:2016-09-05 04:47:43
【问题描述】:
您能否推荐如何正确处理具有许多 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 的用途。
【问题讨论】:
标签: javascript node.js architecture promise structure