Node.js-承诺和锥形语句(if、switch等)-如何构建

Node.js - promises and conidtional statements (if, switch, etc) - how to structure?

本文关键字:构建 何构建 switch if 承诺 js- Node 语句      更新时间:2023-09-26

您能推荐如何正确处理带有许多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