函数在另一个之前执行,但它应该是反过来的吗?

时间:2014-05-22 09:34:12

标签: node.js

我正在学习mongodb和nodejs。这是我的代码:

var databaseUrl = "mydb";
var collections = ["users", "reports"];
var db = require("mongojs").connect(databaseUrl, collections);

safeuser = function() {
    db.users.save(
        {
            email: "john@example.com",
            password: "iLoveMongo",
            sex: "male"
        },
        function( error, saved) {
            if( error || !saved )
                console.log( "User not saved");
            else 
                console.log( "User saved" );
        }
    );
};

finduser = function() {
    db.users.find(
        {
            sex: "male"
        },
        function(error, users) {
            if( error || !users.length )
                console.log( "No male Users found");
            else 
            {
                console.log( "male Users found" );
                users.forEach(
                    function(maleUser) {
                        console.log(maleUser);
                    }
                );
            }
        }
    )
};

safeuser( null, finduser() );

我想要做的是在safeuser()之后执行finduser()。我得到的是:

22 May 21:21:14 - [nodemon] starting `node app.js`
No male Users found
User saved

在safeuser()之前执行finduser()。我想在最后一行代码中我将finduser()设置为safeuser()的回调函数?

2 个答案:

答案 0 :(得分:4)

目前,您在safeuser(null, finduser());运行时立即调用finduser函数。

您需要将引用传递给函数finduser,然后在()函数内调用它(使用safeuser),以使其同步工作。

试试这个:

var databaseUrl = "mydb";
var collections = ["users", "reports"];
var db = require("mongojs").connect(databaseUrl, collections);

saveUser = function(user, cb) {
  db.users.save(user, function(error, saved) {
      if( error || !saved )
        console.log( "User not saved");
      else 
        console.log( "User saved" );
        return cb("male");
    }
  );
};

findUser = function(gender) {
  db.users.find({ sex: gender }, function(error, users) {
      if( error || !users.length ) {
        console.log( "No male Users found");
      } else {
        console.log( "male Users found" );

        users.forEach(function(maleUser) {
          console.log(maleUser);
        });

      }
    }
  )
};

newUser = {
            email: "john@example.com",
            password: "iLoveMongo",
            sex: "male"
          };

saveUser(newUser, findUser);

请注意,finduser作为引用传递给saveUser。然后在saveUser中返回cb()

puddingproof

答案 1 :(得分:0)

对于串行执行,您可以使用灵活的lib http://caolan.github.io/nimble/。很容易简化代码逻辑。

var _ = require('nimble');

//...

newUser = {
        email: "john@example.com",
        password: "iLoveMongo",
        sex: "male"
};

_.series([
    function (callback) {
       saveUser(newUser, function(err, data){
         callback();
       });
    },
    function (callback) {
       findUser();
       callback();
    }
]);