Saturday, 8 April 2017

NodeJS asynchronous callback returns array "undefined"

I am trying to return an array via a callback asynchronously in NodeJS. Unfortunately I am receiving back "undefined".

Here is my code:

var resultTransferData = [];
var buffer = '';

var z = function(roomIds, arrivalDate, departureDate, callback) {

    var postRequest = {
        hostname: "cultswitch.cultuzz.de",
        path: "/cultswitch/processOTA",
        method: "POST",
        port: 8080,
        headers: {
            'Cookie': 'cookie',
            'Content-type': 'application/x-www-form-urlencoded',
        }
    };

    for (var i = 0; i < roomIds.length; i++) {
        var body = 'otaRQ=<?xml version="1.0" encoding="UTF-8"?><OTA_HotelAvailRQ xmlns="http://www.opentravel.org/OTA/2003/05" Version="3.30" TimeStamp="2011-07-12T05:59:49" PrimaryLangID="de"><POS><Source AgentSine="49082" AgentDutyCode="513f3eb9b082756f"><RequestorID Type="10" ID="50114" ID_Context="CLTZ"/><BookingChannel Type="7"/></Source></POS><AvailRequestSegments><AvailRequestSegment ResponseType="RateInfoDetails" InfoSource="MyPersonalStay"><StayDateRange Start="' + arrivalDate + '" End="' + departureDate + '"/><RatePlanCandidates><RatePlanCandidate RatePlanType="11" RatePlanID="' + roomIds[i] + '"/> </RatePlanCandidates><RoomStayCandidates><RoomStayCandidate Quantity="2"><GuestCounts><GuestCount AgeQualifyingCode="10" Count="1"/><GuestCount Age="10" Count="10"/></GuestCounts></RoomStayCandidate></RoomStayCandidates></AvailRequestSegment></AvailRequestSegments></OTA_HotelAvailRQ>';

        var req = http.request(postRequest, function (res) {
            console.log(res.statusCode);
            res.on("data", function (data) {
                buffer = buffer + data;
            });
            res.on("end", function (data) {
                parseString(buffer, function (err, result) {
                    (JSON.stringify(result));
                    resultTransferData.push(result);
                    return callback();
                });
            });
        });
        req.on('error', function (e) {
            console.log('problem with request: ' + e.message);
        });
        req.write(body);
        req.end();
    }
};

var y = function() {
    console.log('i am called inside a function 1');
    return resultTransferData;
};

console.log(z([420420, 420422, 420424, 420426], '2017-09-12', '2017-09-13', y));

My question: Why am I not receiving the array including the data?

If I include

 console.log(resultTransferData);

on line 29 I receive the array with the correct json data.

Thanks for the help.



via Anton Hoerl

No comments:

Post a Comment