2014-10-28 5 views
-1

함수에서 문서의 데이터에 액세스하고 싶습니다. 항목을 처리했는데 어떻게 itemstring에 변수 document.date를 넣을 수 있습니까?부모 함수에서 변수에 액세스하려면 어떻게해야합니까?

function pagelist(items, res) { 
    var db = db_login; 
    result = "<html><body><ul>"; 
    items.forEach(function(item) { 
     console.log(item) 
     db.collection('insights').findById(item._id , function(error, document) { 
      console.log(document) 
      if (error || !document) { 
       res.render('error', {}); 
      } else { 
      **console.log(document.date) //this value is displayed** 
      } 
     }) 

     **console.log(document.date)//this value is undefind** 

     itemstring = "<li>" + item._id + "<ul><li>" + item.textScore + 
      "</li><li>" + item.created + "</li><li>" + item.document + 
      "</li></ul></li>"; 
     result = result + itemstring; 
    }); 
    result = result + "</ul></body></html>"; 
    return result; 
} 
+1

'findById'이 비동기이기 때문에,이 관련 질문을 참조 : HTTP : // 유래 .com/questions/23667086/왜 - 내 - 변수 - 변경되지 않은 - 이후 - 수정 - 그것 - 기능 - 비동기 - 내부 – JohnnyHK

답변

-1

이 시도 : 할당 doc 글로벌 변수와 함수의 외부에서 액세스를 로컬 변수 document;

function pagelist(items, res) { 
    var db = db_login; 
    var doc; 
    result = "<html><body><ul>"; 
    items.forEach(function(item) { 
     console.log(item) 
     db.collection('insights').findById(item._id , function(error, document) { 
     console.log(document) 
     doc=document; // assignment of the local variable to global variable 
     if (error || !document) { 
      res.render('error', {}); 
      } else { 
      console.log(document.date) 
      }}) 

    console.log(doc.date) // here is use of global variable 

    itemstring = "<li>" + item._id + "<ul><li>" + item.textScore + 
     "</li><li>" + item.created + "</li><li>" + item.document + 
     "</li></ul></li>"; 
     result = result + itemstring; 
    }); 
    result = result + "</ul></body></html>"; 
    return result; 
    } 

은 현재 답변 모두가 당신의 "아이"기능이 asyn 기능에서 콜백 즉, 중요한 점을 놓치고 :

0

을 즐길 수 있습니다. "부모"기능의 나머지가 실행되기 전에는 실행되지 않습니다.

function pagelist(items, res) { 
    // ... (1) 
    items.forEach(function(item) { 
     db.collection('insights').findById(item._id, function(error, document) { 
      // this will not execute (4) 
     }); 
     // before this (2) 
    }); 
    // or this (3) 
    // Actual order will be in that of (numbers) 
    return result; 
} 

유일한 옵션은 부모 함수가 db 함수와 동일한 방식으로 작동하게하는 것입니다. 나는. 그것을 asyn으로도 만드십시오.

function pagelist(items, done) { // <= "done" 
    items.forEach(function(item) { 
     db.collection('insights').findById(item._id, function(error, document) { 
      // Now you can call done with document that is available here 
      done(document); // or done(document.date); w/e 
     }); 
    // return result; // Returns are useless* in asyncs 
} 

당신이 "완료"콜백 함수를 전달할에서 pagelist()를 호출하고 거기에 물건을하고 어디

app.use(function(req, res){ 
    pagelist(items, function(document){ // <= this will be the "done" function 
     var itemstring = document.date; 
     // do whatever you want with the document here. 
     res.render(~); 
     console.log(document.date); 
    }); 
}); 
관련 문제