3

node.js が非同期で実行されることはわかっているため、外側の関数は内側よりも先に実行されます。しかし、for ループの外で通知配列にアクセスするにはどうすればよいでしょうか? 配列内のすべての値に一度にアクセスしたいのですが、これは可能ですか?

var notification=[];

for(var j=0;j<6; j++)
{
     getNotification(response[j].sender_id,function(results)     // a function called
     {
         notification[j] =results;
         console.log(notification); // output: correct   
     });          
}
console.log(notification);       // output: [], need notification array values here
4

3 に答える 3

1

編集: サードパーティのライブラリを使用したくない場合は、独自のコードでこれを行う方法を次に示します。

/* jshint node:true*/


function getNotifications(responses, callbackToMainProgramLogic) {
    'use strict';
    var results = [];

    function getNotificationAsync(response) {
        getNotification(response.sender_id, function (data) {
            results.push(data);

            if (responses.length) {
                getNotificationAsync(responses.pop());//If there are still responses, launch another async getNotification.
            } else {
                callbackToMainProgramLogic(results);//IF there aren't we're done, and we return to main program flow
            }
        });
    }

    getNotificationAsync(responses.pop());
}

getNotifications(someArrayOfResonses, function (dataFromNotifications) {
    console.log('The collected data: ' + JSON.stringify(dataFromNotifications, 0, 4));
});

どうしてもやむを得ない場合は、このようなばかげたことをすることができます。loopUntilDatReceived のロジックは、空でない文字列を待つのではなく、配列サイズを待つことになりますが、考え方は似ており、とにかくこれを使用するべきではありません! :)

var fileData = '';
fs.readFile('blah.js', function (err, data) { //Async operation, similar to your issue.
    'use strict';
    fileData = data;
    console.log('The Data: ' + data);
});

function loopUntilDataReceived() {
    'use strict';
    process.nextTick(function () {//A straight while loop would block the event loop, so we do this once per loop around the event loop.  
        if (fileData === '') {
            console.log('No Data Yet');
            loopUntilDataReceived();
        } else {
            console.log('Finally: ' + fileData);
        }
    });
}

loopUntilDataReceived();

これはばかげていると言いましたか?正直なところ、これはひどい考えですが、何が起こっているのか、Node イベント ループがどのように機能するのか、そしてなぜあなたが望むことができないのかを理解するのに役立つかもしれません。そして、コールバックとフロー制御ライブラリに関する他の投稿が進むべき道である理由.

于 2013-08-02T13:35:16.810 に答える
0

次のように、通知ループにコールバックを送信します。

var notification=[];

getNotificationArray( function() {
  console.log(notification);
});

function getNotificationArray (callback)
{
  for(var j=0;j<6; j++)
  {
    getNotification(response[j].sender_id,function(results)     // a function called
    {
      notification[j] =results;
      console.log(notification); // output: correct   
    });          
  }
  callback();
}
于 2013-08-02T13:32:25.100 に答える