2016-06-27 1 views
2
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(); 
     } 
    }); 
    }, 

Эта функция работает почти правильно, но линия:NodeJS является асинхронным и мой код не работает в порядке, я ожидал

 data.save(); 

работает, прежде чем заканчивает предыдущая строка, которая означает, что данные Я хочу сохранить, нет в соответствующее время.

 data.mongo_id = userCreationCtrl(account); 

Эта строка вызывает функцию, которая создает документ MongoDB с информацией в объекте учетной записи, а затем возвращает _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; 
+1

Вы можете разместить содержимое функции 'userCreationCtrl'? –

+0

Да, я отредактировал его в исходном вопросе. –

+1

'userCreationCtrl' принимает 3 аргумента, и вы передаете только 1. Вместо того, чтобы возвращать из него' result._id', просто вызывайте обратный вызов с этим результатом, а также внутри этого обратного вызова 'data.save()' –

ответ

2

У вас есть userCreationCtrl ожидающих 3 аргументов, account, res и next. 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(); 
    }); 
    } 
}); 
+1

Это все прекрасно и денди, но если 'userCreateCtrl()' на самом деле 'createNewUser()' в коде OP, опубликованном, то 'createNewUser()' не использует обратный вызов для связи, когда это делается, так что это всего лишь одна часть что нужно сделать. – jfriend00

+0

вот что моя первая строка кода относится к ... replace 'return result._id;' с 'next (null, result._id);' – Ryan

+0

userCreateCrtl() действительно createNewUser() Возможно, я бы назвал их то же самое для ясности ... –

Смежные вопросы