0

I am newbie to nodejs.It's very hard to handle callbacks at nodejs level. I have code like this,

getItems(request,function(jsonObject){
     var itemData={};
     var itemDetails=new Array();
     for(var i=0;i < jsonObject.length;i++){
         getItemDetails(jsonObject[i].value.item_id,function(jsonObject){
            itemDetails.push(jsonObject);
         });
    }
    itemData["itemDetails"]=itemDetails;
    response.contentType("application/json");
    response.send({"data":itemData});
});

while executing the above code, the for loop is continuing with out getting callback from getItemDetails method and response sent to client. My requirement is the loop will wait until getting the call back from the getItemDetails then response should send. I have tried with process.nextTick(), but i am unable to find where i have to use that process.nextTick().. Please anybody provide suggestions.

Thanks in advance.

4

2 回答 2

1

您只需要在获得所有项目后发送响应,因此修改您的代码,如下所示:

getItems(request,function(jsonObject) {
    var itemData = {},
        itemDetails = [],
        itemsLeft = len = jsonObject.length,
        i;

    function sendResponse(itemDetails) {
        itemData["itemDetails"] = itemDetails;
        response.contentType("application/json");
        response.send({ "data": itemData });
    }

    for (i = 0; i < len; i++) {
        getItemDetails(jsonObject[i].value.item_id, function(jsonObject) {
            itemDetails.push(jsonObject);
            // send response after all callbacks have been executed
            if (!--itemsLeft) {
                sendResponse(itemDetails);
            }
        });
    }
});

注意:我在itemLeft这里使用它是因为它是解决这类问题的一种更通用的方法,但 Ianzz 方法也可以,因为您可以比较两个数组的长度。

于 2012-06-07T13:24:57.090 回答
0

您不能让循环等待,但您可以修改代码以获得您期望的行为:

getItems(request,function(outerJsonObject){
    var itemData={};
    var itemDetails=new Array();
    for(var i=0;i < outerJsonObject.length;i++){
        getItemDetails(jsonObject[i].value.item_id,function(innerJsonObject){
            itemDetails.push(innerJsonObject);
            if (itemDetails.length == outerJsonObject.length) {
                // got all item details
                itemData["itemDetails"]=itemDetails;
                response.contentType("application/json");
                response.send({"data":itemData});
            }
        });
    }
});
于 2012-06-07T13:20:28.657 回答