【问题标题】:Node.js - promises and conidtional statements (if, switch, etc) - how to structure?Node.js - 承诺和条件语句(if、switch 等) - 如何构建?
【发布时间】: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


    【解决方案1】:

    我觉得用generator比较好,然后你可以写sync之类的代码:

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

    可以配合callback和promise,见https://github.com/tj/co

    【讨论】:

    • 感谢您的想法,但如果没有必要,我宁愿坚持使用 Promises,也不要添加更多依赖项。
    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 2016-03-02
    • 1970-01-01
    • 2020-05-01
    • 2019-07-04
    • 1970-01-01
    • 2023-04-08
    • 2018-05-18
    相关资源
    最近更新 更多