2017-03-14 6 views
0

나는이 루프를 며칠 동안 수수께끼로 썼다. 그리고 내가 필요한 것을 얻지는 못했다.배열에있는 객체에 새로운 요소 추가하기

검색 결과 배열 (mdb_results)을 반복하고 각 객체에서 .name을 추출하여 Google CSE 이미지 검색에서 _search 용어로 사용합니다.

Th CSE는 _search 용어 (mdb_results[i])를 추출한 개체에 추가 할 다른 배열 (cse)을 반환합니다.

router.get('/json', function(req, res, next) { 
var ImageSearch = require('node-google-image-search'); 
MongoClient.connect(url, function(err,db){ 
    db.collection('mycatalog') 
    .find({$text: {$search:"FOO" }}) 
    .toArray(function(err, mdb_results){  
     for (var i=0; i<mdb_results.length; i++){   
      var _search = mdb_results[i].name ; 

      ImageSearch(_search, function(cse){ 

       // How to add cse.img to mdb_results[i].images ?? 
       // mdb_results[i].images = cse; 
       // gives undefined 

      },0,2); 
     }; 
     res.send(mdb_results); 
     }); 
    }); 
}); 

내 초기 mdb_results은 다음과 같습니다.

[{"name":"FOO"},{"name":"FOOOO"}] 

나는 이런 식으로 뭔가를 달성하기 위해 노력하고있어,

[{"name":"FOO", 
    "images":[{"img1":"http://thumbnail1"},{"img2":"http://thumbnail2"}] 
}, 
{"name":"FOOOO", 
    "images":[{"img1":"http://thumbnaila"},{"img2":"http://thumbnailb"}] 
}] 

사람이 어떻게 이것을 달성하는 저를 게재 할 수 있습니까? 당신은 약속이나 async 라이브러리를 사용하기 위해 필요 해요

router.get('/json', function(req, res, next) { 
var ImageSearch = require('node-google-image-search'); 
MongoClient.connect(url, function(err,db){ 
    db.collection('mycatalog') 
    .find({$text: {$search:"FOO" }}) 
    .toArray(function(err, mdb_results){  
     for (var i=0; i<mdb_results.length; i++){   
      var _search = mdb_results[i].name ; 
      // This search is asynchronous, it won't have returned by the time 
      // you return the result below. 
      ImageSearch(_search, function(cse){ 

       // How to add cse.img to mdb_results[i].images ?? 
       // mdb_results[i].images = cse; 
       // gives undefined 

      },0,2); 
     }; 
     // At this point, ImageSearch has been called, but has not returned results. 
     res.send(mdb_results); 
     }); 
    }); 
}); 

:

감사

답변

1

문제는 비동기 작업이 동 기적으로 작동을 기대하고 있다는 것입니다. 감사 -이 작동하고 내가 대답을 받아

router.get('/json', function(req, res, next) { 
var ImageSearch = require('node-google-image-search'); 
MongoClient.connect(url, function(err,db){ 
    db.collection('mycatalog') 
    .find({$text: {$search:"FOO" }}) 
    .toArray(function(err, mdb_results){ 
     // async.forEach will iterate through an array and perform an asynchronous action. 
     // It waits for you to call callback() to indicate that you are done 
     // rather than waiting for it to execute synchronously. 
     async.forEach(mdb_results, function (result, callback) { 
      ImageSearch(result.name, function(cse){ 
       // This code doesn't get executed until the network call returns results. 
       result.images = cse; 
       // This indicate that you are done with this iteration. 
       return callback(); 
      },0,2); 
     }, 
     // This gets call once callback() is called for each element in the array, 
     // so this only gets fired after ImageSearch returns you results. 
     function (err) { 
      res.send(mdb_results); 
     }); 
    }); 
}); 
+0

:

다음은 예입니다. 'cb '로 무슨 일이 일어나고 있는지 좀 더 자세히 설명해 주시겠습니까? 작동에도 불구하고, 나는 일어나고있는 일을 이해하기 위해 고심하고 있습니다. – Colin

+0

난 정교를하려고 게시물을 업데이 트했습니다. NodeJS에서 콜백이 작동하는 방식을 이해하는 것은 여기서 일어나는 일을 이해하는 데 중요합니다. 콜백은 작업이 완료되었음을 나타 내기 위해 사용됩니다. – EmptyArsenal

+0

주석 주셔서 감사합니다. 나는 여전히 자신에게 전화하는 것으로 보이는'return callback() '으로 고민 중이다. 우리는'콜백 (callback) '을 둘러싸는 함수에 넘겨주고'callback'에 대한 함수 정의없이 호출합니다. 대답이 너무 복잡하여 의견을 듣지 못하는 경우 직접 교육 할 수있는 리소스를 추천 해 주실 수 있습니까? – Colin