2

node.js用のMongoJSドライバーを使用してデータを取得しようとしています。使用しているコードは次のとおりです。

     req.on('end', function(){
             var decodedBody = querystring.parse(fullBody);
             story=decodedBody.name;
             var z=new Array();
             console.log(story);
         res.writeHead(200,{'Content-Type': 'text/html'});
         res.write('<html><body>');
             db.frames.find({str_id:story}).toArray(function(err,doc){
             console.log(doc);
             for(var t=0;t<doc.length;t++)
                 {
                     var picid=doc[t].pic_id;
                     console.log(picid);               
                     db.pictures.find({_id:picid}).toArray(function(err,pic){
                      res.write('<img src="'+pic[0].name+'"/>');
             });
           } 
        }) 
        res.end('</body></html>'); 
   });

ここでの問題は、コードの非同期性のために応答が最初に終了し、次にデータベースのブロック内のコードが実行され、そのためブラウザに何も表示されないことです。この場合は画像です。よろしくお願いします。

4

2 に答える 2

3

node.js の非同期性と戦うのではなく、受け入れてください!

そのため、すべてのリクエストを開始し、レスポンスが到着したときにそれぞれを完了としてマークする必要があります。すべてのリクエストが完了したら、画像と body/html 終了タグをレンダリングします。

私は通常、node.js を使用しないので、間違いを犯す可能性がありますが、次のようになる可能性があります。

res.write('<html><body>');
db.frames.find({str_id:story}).toArray(function(err,doc){
  console.log(doc);

  var completed = {};

  for(var t = 0; t < doc.length; t++) {
    var picid = doc[t].pic_id;
    completed.picid = false;
    console.log(picid);               
    db.pictures.find({_id: picid}).toArray(function(err, pic) {
      // mark request as completed
      completed.picid = pic;


      // check if all requests completed
      var all_finished = true;
      for(var k in completed) {
        if(completed[k] === false) {
          all_finished = false;
          break;
        }
      }

      // render final markup
      if(all_finished) {
        for(var k in completed) {
          var pic = completed[k];
          res.write('<img src="'+pic[0].name+'"/>');
        }
        res.end('</body></html>);
      }
    });


  } 
}) 
于 2012-10-18T07:05:09.947 に答える
1

res.end('</body></html>');関数の中に入れるだけdb.frames.findです。到達doc.length - 1したことを確認してから、コマンドを送信してくださいend

于 2012-10-18T07:01:53.303 に答える