NodeJS 是异步的,我的代码没有按我期望的顺序 运行

NodeJS is asynchronous and my code doesn't run in the order I am expecting

  postRegistrationHandler: function (account, req, res, next) {
    console.log('postRegistrationHandler activated');
    account.getCustomData(function(err, data) {
      if (err) {
        console.log(err.toString, "error string");
        return next(err);
      } else {
        data.mongo_id = userCreationCtrl(account);
        data.save();
        next();
      }
    });
  },

这个函数几乎可以正常工作,但是行:

        data.save();

在上一行完成之前运行,这意味着我要保存的数据没有在适当的时间出现。

        data.mongo_id = userCreationCtrl(account);

此行调用了一个函数,该函数创建一个 mongoDB 文档,其中包含帐户对象中的信息,然后 returns _id(这是我要保存的内容。

我想也许使用 .then() 会有所帮助,但由于某种原因,这里似乎不可用。如果有人看到我遗漏的东西,那将非常有帮助。谢谢!

这里是请求的userCreationCtrl文件:

var UserSchema = require('./../models/UserModel.js');

var createNewUser = function (account, res, next){
  // We will return mongoId after it is created by submitting a newUser
  var mongoId = "";
  // Save StormpathID (last 22 characters of account.href property)
  var newStormpathId = account.href.slice(account.href.length - 22);
  console.log('stormpath ID:', newStormpathId, 'just registered!');
  console.log(account);
  // Create new user from model by recycling info from the Stormpath registration form and include the stormpathId as well.
  var newUser = new UserSchema({
      stormpathId: newStormpathId,
      firstName: account.givenName,
      lastName: account.surname,
      email: account.email,
      street: account.street,
      city: account.city,
      zip: account.zip
  });
  // This saves the user we just created in MongoDB
  newUser.save(function(err, result){
      console.log(result);
      if (err) {
            console.error(err);
      }
      else {
        console.log("User created in MongoDB, attempting to return mongoDB _id to stormpath customData");
        // Keep track of the new user's mongo _id so we can return it to the previous function and save it as Stormpath custom data.
        mongoId = result._id;
        console.log(mongoId, "mongoid");
        return result._id;
      }
  });
};

module.exports = createNewUser;

userCreationCtrl 需要 3 个参数,accountresnextnext 是创建用户后应调用的回调,因此您应该像这样调用 next 而不是 return result._id

// inside of createNewUser()
newUser.save(function(err, result){
  console.log(result);
  if (err) {
    console.error(err);
  }
  else {
    console.log("User created in MongoDB, attempting to return mongoDB _id to stormpath customData");
    // Keep track of the new user's mongo _id so we can return it to the previous function and save it as Stormpath custom data.
    mongoId = result._id;
    console.log(mongoId, "mongoid");

    // IMPORTANT change to make it all work...
    // get rid of return result._id because its not doing anything
    // pass the value to your callback function instead of returning the value
    next(null, result._id);
  }
});

那么 postRegistrationHandler 中的调用代码应该如下所示:

account.getCustomData(function(err, data) {
  if (err) {
    console.log(err.toString, "error string");
    return next(err);
  } else {
    // pass in a callback as the 3rd parameter that will be called by newUser.save() when its finished
    userCreationCtrl(account, null, function(err, resultId) {
      data.save();
      next();
    });
  }
});