노드 js가 비동기이며이 문제를 해결하기 위해 많은 리소스를 보았습니다. 내 문제는, 나는이 mongodb 쿼리를 실행 해요,하지만 쿼리가 끝나기 전에 내 함수가 반환 약속에 대해 알고 있고 그들을 사용하고 있지만 작동하지 않는, 내가 뭘 잘못하고있다.코드에서 노드 js에서 함수 반환을 기다리는 방법
function findConversation(Id){
return new Promise(function(resolve, reject){
ConversationSchema.find({ 'participants.Id': Id }, function (err, conversations) {
if (err) return reject(err);
if (conversations) {
console.log("Conversation JSON: " + conversations)
}
resolve(conversations)
})
\t })
}
이 내가 실행 해요 쿼리이지만,이 울부 짖는 소리 함수라고 : 내 코드는 아래에서 확인할 수 있습니다
function getConversations(user){
\t var newConversations = []
\t query.findConversation(user.userName).then(function(convers) {
\t \t if(convers) {
\t \t \t console.log("conversation was found: " + convers)
\t \t \t newConversations = convers
\t \t }
\t \t else {
\t \t \t console.log("conversation was not found: " + convers)
\t \t }
\t }).catch(function(reason) {
\t \t console.log("failure when finding conversation: " + reason)
\t })
\t return newConversations
}
위의 함수는 약속을 기다리지 않고 반환하는 함수입니다. L이 기능 :
socket.on(VERIFY_USER, (nickname, callback)=>{
query.userExist(nickname).then(function(user){
if(user){
console.log("user exist")
var conversation = factories.getConversations(user)
console.log("Existing user Conversations: " + conversation)
callback({ userExist:true, user:factories.getUser(user, socket.id), conversations: conversation})
}
else {
console.log("user does not exist")
callback({ userExist:false, user:factories.createUser(nickname, socket.id), conversations:[]})
}
}).catch(function(reason) {
console.error(reason);
})
\t })
약속은 쿼리의 반환을 기다리지 않기 때문에 그래, 나는 또한 동일한 문제 ...와 싸우고있다 –