Nodejs没有参数的异步函数

时间:2018-03-27 13:30:20

标签: node.js http express asynchronous rethinkdb

我正在开发一个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"如果没有那个第二个变量,我就无法调用"回调(结果)"最后得到错误"回调不是函数"。

<小时/> 所以,我的整体问题是,是否有一种方法可以在没有第二个参数的情况下创建异步函数! 非常感谢你:))

2 个答案:

答案 0 :(得分:1)

您必须从函数定义和函数调用中删除“not needed”参数:

getChain(callback) {

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

答案 1 :(得分: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一起使用。
  • 如果要使用回调,请将错误传递给回调。按照惯例,第一个回调参数应始终为error或null如果一切正常。
  • 看看承诺及其运作方式