Node.js - promises和conidtional语句(if,switch等) - 如何构造?

时间:2016-05-10 09:36:59

标签: javascript node.js architecture promise structure

您能否建议如何使用if / switch和promises正确处理控制流?我发现的互联网上的所有教程都倾向于处理简单的控制流程,而没有很多(任何?)不同的处理分支。任何建议的阅读或至少搜索条件?

我现在的方法是在评估条件并返回主进程循环后,将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的用途。

1 个答案:

答案 0 :(得分:0)

我认为最好使用生成器,然后你可以像代码一样编写同步:

co(function* () {
   // Check if argument is a valid URL
   if (yield checkUrl) {
       var cleanUrl = yield sanitizer.cleanAsync(argv.url);
       ...
   }
   ...
}, ...

co可以与回调和承诺合作,请参阅https://github.com/tj/co