【问题标题】:Nodejs Asynchronous function without parameterNodejs 无参数异步函数
【发布时间】:2018-09-05 22:38:49
【问题描述】:

我正在开发一个 rethinkDB 数据库,并使用快速服务器和 HTTP 请求访问它。

据我所知,从数据库中获取数据然后响应 HTTP 请求需要一个异步函数。

我的看起来像这样:

getChain(notNeeded, callback) {
        // Connecting to database
        let connection = null;
        rethinkdb.connect({ host: 'localhost', port: 28015 }, (err, conn) => {
            if (err) throw err;
            connection = conn;
            rethinkdb.db(dbUsed).table(tableUsed).run(connection, (err, cursor) => {
                if (err) throw err;
                cursor.toArray((err, result) => {
                    if (err) throw err;
                    // console.log(JSON.stringify(result, null, 2));
                    console.log(result + "1");
                    callback(result);
                })
            })
        })

    }

我通过以下方式访问它:

router.get('/', (req, res, next) => {
    DatabaseBlockchain.getChain(('not needed'), callback => {
        res.status(200).json(callback);
    }) 
})

如您所见,有一个变量“不需要”,我不需要。
但是当没有第二个变量创建“getChain”时,我不能在最后调用“callback(result)”并得到“回调不是函数”的错误。


所以,我的总体问题是,是否有办法在没有第二个参数的情况下创建异步函数!
非常感谢 :)

【问题讨论】:

    标签: node.js http express asynchronous rethinkdb


    【解决方案1】:

    是的,这是可能的。回调的行为与其他所有参数一样。

    getChain(callback) {
            // Connecting to database
            let connection = null;
            rethinkdb.connect({ host: 'localhost', port: 28015 }, (err, conn) => {
                if (err) throw err;
                connection = conn;
                rethinkdb.db(dbUsed).table(tableUsed).run(connection, (err, cursor) => {
                    if (err) throw err;
                    cursor.toArray((err, result) => {
                        if (err) throw err;
                        // console.log(JSON.stringify(result, null, 2));
                        console.log(result + "1");
                        callback(result);
                    })
                })
            })
    
        }
    

    然后调用它

    router.get('/', (req, res, next) => {
        DatabaseBlockchain.getChain(callback => {
            res.status(200).json(callback);
        }) 
    })
    

    需要注意的几点:

    • 除非您使用 async/await,否则异步错误处理不适用于 throw。
    • 如果要使用回调,请将错误传递给回调。按照惯例,如果一切正常,第一个回调参数应始终为错误或 null。
    • 查看 Promise 及其工作原理

    【讨论】:

    • 哇,谢谢!我以为我试过了,但似乎我也改变了其他东西。现在效果很好!也感谢您的提示,我会尽力改进!
    【解决方案2】:

    您必须从函数定义和函数调用中删除“不需要”的参数:

    getChain(callback) {
    

    还有:

    DatabaseBlockchain.getChain(result => {
        res.status(200).json(result);
    }) 
    

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      相关资源
      最近更新 更多