将异步响应推送到NodeJS中的数组中

时间:2016-12-12 07:27:07

标签: javascript arrays node.js asynchronous

我有一个元素数组,我通过它迭代并进行一些RPC调用来获取响应,将响应推送到数组并将其发送回UI进行显示。但这些响应是异步的,不会被推入数组。因此,当在UI端收到响应时,它是空的。

NodeJS代码:

app.get('/getData/:obj', function(req,res, next){

    data = JSON.parse(req.params.obj);

    var options = ["location","start","end","user"];

    /*Data looks like this*/

    /*[ { start: '12-05-2016' },
      { end: '12-09-2016' },
      { location: [ 'US','UK' ] },
      { user: [ 'Jim','Jack' ] } ]*/

    var requestArray = [];
    for(var d in data) {
        if(options.indexOf(d) > -1 ) {
            var rpcRequest = {};
            rpcRequest[d] = data[d]
            requestArray.push(rpcRequest);
        }

    }
    console.log(requestArray);
    var resp = []

    for(var i in requestArray)    {
        var item = requestArray[i];
        _.each(item, function(value, key) {
            console.log('key :'+key+'\tvalue: '+value);
            if(util.isArray(value)) {
                for(var val in value)   {
                    var request = {};
                    request[key] = value[val];
                    console.log('\tkey :'+key+'\tvalue: '+value[val]);
                    console.log('request: '+JSON.stringify(request));

                    switch(key) {
                        case "location": 
                            rpcClient.location(request, function(err, response) {

                                response = (JSON.stringify(response)); //asynchronous  response

                                resp.push(response); //push response into array

                            });
                            break;
                        case "user":
                            rpcClient.user(request, function(err, response) {

                                response = JSON.stringify(response); //asynchronous  response

                                resp.push(response); //push response into array

                            });
                            break;

                        default: break;
                    }


                }
            }

        });

    }

    console.log(resp);
    res.send({d:resp}); // send the response array, but it is empty
}); 

如何将数据推送到阵列同步或以某种方式获取正确的数据。我听说过异步模块,坚果不太清楚如何在这里使用它。

寻求帮助!谢谢:))

1 个答案:

答案 0 :(得分:0)

您等到res.send,直到收到最后一个回复为止。

因此,您要跟踪已收到的回复数量,当您收到最后一回复然后时,您会在响应回调中针对该最终回复致电res.send

这是一个简单的例子:



var requests = [
  "one", "two", "three", "four", "five"
];
var responses = [];
requests.forEach(function(request) {
  // setTimeout to get something async
  setTimeout(function() {
    // Now we're in the async operation callback
    var response = "Response for " + request;
    console.log("Got: " + response);
    
    // Save the response
    responses.push(response);
    
    // Is it the last one?
    if (responses.length == requests.length) {
      // We're done, this is where you'd do
      // `res.send`
      console.log("Done! Got all responses: ", responses);
    }
  }, Math.random() * 1000);
});




旁注:不要使用for-in循环遍历数组,除非你因为稀疏数组而故意这样做;那不是它的意思。有关循环数组的各种选项,请参阅this question's个答案。