I've been discovering Node through Express (instead of Meteor I used to use). And I am cornered by a kind of asynchronous-thing..

我一直在通过Express发现Node(而不是我曾经使用的Meteor)。而我被一种异步的东西逼入绝境......

Below a function (to read a mongo collection)

下面是一个函数(读取mongo集合)

function isAuthorized(x) {

        // Connect to database when Bq. receives a message
        mongoClient.connect(process.env.MONGO, function (err, db) {

            if (err) {
                console.log('Unable to connect to the mongoDB server')
            } else {
                console.log('Connection established')
                let Users = db.collection('users')
                Users.find( {_id: From} ).toArray(function (err, result) {
                    if (err) { console.log(err) }
                    else if (result.length) {
                        console.log("found");
                        // switch (true) {
                        //     case x == null && result.authorization == null : return true
                        //     break ;
                        //     case x == false && result.authorization == false : return true
                        //     break ;
                        //     case x == true && result.authorization == true : return true
                        //     break ;
                        //     default: return false
                        //} // end of switch()
                    }
                    else {
                        console.log("does not exist");
                        if (x == 'unknown user') { console.log("return true"); return true }
                    }
                    db.close()
                })
            }
        })
    } // end of isAuthorized()

This function is called into a switch().

该函数被调用为switch()。

switch (true) {

        case isAuthorized('unknown user') : something
        case XYZ
        case ABC
        Default: console.log("default") 
}

The problem is: the switch() fires before the end of the isAuthorized() function. Thus, the switch() fires the default case (instead of isAuthorized('unknown user') == true). The function doesn't seem to wait for the database to be read...

问题是:switch()在isAuthorized()函数结束之前触发。因此,switch()触发默认情况(而不是isAuthorized('unknown user')== true)。该函数似乎没有等待数据库被读取...

How it is possible to make the switch() wait for the very end of the function isAuthorized()?

如何使switch()等待函数的最终结束isAuthorized()?

I've heard about callback-think, async, but I'm not able to sort all this thing in a clear order.. Any simple idea/help?

我听说过回调 - 想想,异步,但我无法按照明确的顺序对所有这些事情进行排序..任何简单的想法/帮助?

Thank you very much.

非常感谢你。

1 个解决方案

#1


1

Short answer

The way your code is currently structured, this is not possible. See async & await

您的代码目前的结构方式,这是不可能的。请参阅async和await

Long answer

As you've already stated, you'd need to use callbacks. In your example, you'd have to check if the user is authorized first and then run the switch statement.

正如您已经说过的,您需要使用回调。在您的示例中,您必须首先检查用户是否已获得授权,然后运行switch语句。

Pseudo Code:

function isAuthorized(user, callback) {

    // Run your mongoDB logic
    mongoClient.connect(process.env.MONGO, function (err, db) {
        Users.find({ _id: From }).toArray(function (err, result) {
            var authorized = ...check if user is authorized...
            db.close();
            callback(authorized);
        });
    });
}

and then use it like that:

然后像这样使用它:

isAuthorized(yourUser, function (authorized) {
    if (authorized) {
        // business logic
    }
});

I hope this clears out some things for you.

我希望这能为你清除一些事情。

更多相关文章

  1. JavaScript(ES5)使用保留字作函数名
  2. 将JavaScript函数的值插入SQL Server数据库
  3. 轮播图---可以动态添加图片,(封装成一个函数)
  4. javascript高阶函数map和reduce
  5. jQuery插件:如何将元素引用传递给回调函数?
  6. Javascript等待函数的结束,包括node.js的异步MYSQL查询?
  7. JavaScript数组操作函数方法详解
  8. JavaScript:使用函数参数检索javascript对象键
  9. 由浅到深的分析Javascript OO之写类方式之一:构造函数

随机推荐

  1. android 背景圆角以及图片圆角处理
  2. 通过API级别进行文档内容过滤
  3. [Android学习]ImageView的scaletype属性
  4. Android布局图标中心化
  5. android IApplicationToken分析
  6. 11月29日
  7. Android中接口的使用及类使用
  8. Android 版本号和分支查看
  9. Android使用VideoView全屏播放视频拉伸变
  10. android学习资料与资源记录