ノード アプリで関数を実行していますが、非同期コードを適切に記述する方法を理解していないために機能しません。以下は、メールでプロファイルを取り込む関数です。各メールをループして、そのユーザーがデータベースに存在するかどうかを確認したいと思います。もしそうなら、与えられたコールバックを返し、他に何もせずに関数を完全に存在させたいと思います。ユーザーが見つからない場合は、プロファイルで指定された情報に基づいて新しいユーザーを作成し、新しく作成されたユーザーと同じコールバックを返します。現在、データベースでユーザーが既に見つかっている場合でも新しいユーザーを作成することを除いて、関数は意図したとおりに機能します。(「ユーザー」変数は上記で定義されており、「作成」機能があります。また、「非同期」の使用を避けたいと思います
function processProfile(profile, callback) {
var existingUser;
if (profile.emails) {
profile.emails.forEach(function(email) {
console.log("Searching for user with this email:" + email.value);
existingUser = findUserByEmail(email.value);
if (existingUser) {
console.log("Found the existing user");
return callback(null, existingUser);
}
});
if(!existingUser){
console.log("Creating new user");
var newUser = {
id: profile.id,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
email: profile.emails[0].value
};
user.create(newUser, profile.provider, function(err, user) {
if (err) throw err;
return callback(null, user);
});
}
}
}