AWS在回调中返回回调

时间:2016-09-10 02:31:37

标签: javascript node.js amazon-web-services

我想在AWS功能的主要部分返回一个值。我无法从第一次回调中获取数据,因此我可以将其发送到最后一个回调。

  /** module used for outbound http requests */
    var request = require('request');

    /** module used for parsing XML easily. https://www.npmjs.com/package/xml2js*/
    var parseString = require('xml2js').parseString;
exports.handler = (event, context, callback) => {

    // testing array of coordinates
    var arrayOfPoints = [39.7683800, -86.1580400, 41.881832, -87.623177];
    var results = getXMLFromNOAA(arrayOfPoints);
    callback(null, results); // <- returns 'undefined' in the AWS console. I'm assuming race condition.
};

/**
* getXMLFromNOAA
*
* This is a function used for figuring out the functionality of NOAA XML parsing
*
* @param arrayOfPoints {Array[Double]} - An evenly numbered index array of latitudes and longitudes
*
* @return result {XML/JSON} - weather information abled to be parsed
*/
function getXMLFromNOAA(arrayOfPoints, callback) {

    var baseURL = "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?whichClient=NDFDgenLatLonList&lat=&lon=&listLatLon=";

    // for-loop getting all points and dynamically adding them to the query url string
    // iterate 2 at a time since they are coupled coordinates (e.g. [lat1, lng1, lat2, lng2, ... latN, lngN])
    for(var i = 0; i < arrayOfPoints.length; i = i + 2)
    {
        // if we're at the end of the arrayOfPoints, finish up the chain of query coordinates
        if( (i+2) == arrayOfPoints.length)
        {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i+1]);
        } 
        else 
        {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i+1]);
            baseURL = baseURL.concat("+");
        }
    }

    // TIME
    baseURL = baseURL.concat("&lat1=&lon1=&lat2=&lon2=&resolutionSub=&listLat1=&listLon1=&listLat2=&listLon2=&resolutionList=&endPoint1Lat=&endPoint1Lon=&endPoint2Lat=&endPoint2Lon=&listEndPoint1Lat=&listEndPoint1Lon=&listEndPoint2Lat=&listEndPoint2Lon=&zipCodeList=&listZipCodeList=&centerPointLat=&centerPointLon=&distanceLat=&distanceLon=&resolutionSquare=&listCenterPointLat=&listCenterPointLon=&listDistanceLat=&listDistanceLon=&listResolutionSquare=&citiesLevel=&listCitiesLevel=&sector=&gmlListLatLon=&featureType=&requestedTime=&startTime=&endTime=&compType=&propertyName=&product=time-series&begin=2016-09-04T00:00:00&end=2016-09-11T00:00:00");

    // CHARACTERISTICS REQUESTED
    // http://graphical.weather.gov/xml/docs/elementInputNames.php
    baseURL = baseURL.concat("&Unit=e&maxt=maxt&mint=mint&temp=temp&appt=appt&rh=rh&sky=sky&wwa=wwa&iceaccum=iceaccum&ptornado=ptornado&phail=phail&ptstmwinds=ptstmwinds&pxtornado=pxtornado&pxhail=pxhail&ptotsvrtstm=ptotsvrtstm&wgust=wgust");

    // Used for testing and seeing the final result
    console.log(baseURL);

    request(baseURL, function (error, response, body) 
    {
        if (!error && response.statusCode == 200) 
        {
            parseString(body, function (err, result) {
                console.log('inside parseString: ' + result); // <- this prints but it won't show up in the main
                // callback(null, result); <- doesnt work
                return result; // doesnt work either
            });
        }
    })
}

我希望能够使我的代码更具模块化以实现可伸缩性。我知道有一种方法可以采用getXMlFromNOAA的异步过程并迭代地执行它们。我对JavaScript的熟悉程度并不像我应该的那样熟悉。任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:2)

您可以使用async module使其更具可读性和灵活性,并且不会出现异步问题。 写下你的东西

/** module used for outbound http requests */
var request = require('request');
var async = require('async');

/** module used for parsing XML easily. https://www.npmjs.com/package/xml2js*/
var parseString = require('xml2js').parseString;
exports.handler = (event, context, callback) => {

    async.waterfall([

        function(next) {
            // testing array of coordinates
            var arrayOfPoints = [39.7683800, -86.1580400, 41.881832, -87.623177];
            var results = getXMLFromNOAA(arrayOfPoints, next);

        },
        function(baseURL, next) {

            request(baseURL, function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    parseString(body, function(err, result) {
                        console.log('inside parseString: ' + result); // <- this prints but it won't show up in the main
                        if (!err)
                            next(null, result);
                    });
                }
            })

        }
    ], function(err, result) {
        if (!err) {
            callback(null, results); // <- returns 'undefined' in the AWS console. I'm assuming race condition.
        }

    })

};

/**
 * getXMLFromNOAA
 *
 * This is a function used for figuring out the functionality of NOAA XML parsing
 *
 * @param arrayOfPoints {Array[Double]} - An evenly numbered index array of latitudes and longitudes
 *
 * @return result {XML/JSON} - weather information abled to be parsed
 */
function getXMLFromNOAA(arrayOfPoints, next) {

    var baseURL = "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?whichClient=NDFDgenLatLonList&lat=&lon=&listLatLon=";

    // for-loop getting all points and dynamically adding them to the query url string
    // iterate 2 at a time since they are coupled coordinates (e.g. [lat1, lng1, lat2, lng2, ... latN, lngN])
    for (var i = 0; i < arrayOfPoints.length; i = i + 2) {
        // if we're at the end of the arrayOfPoints, finish up the chain of query coordinates
        if ((i + 2) == arrayOfPoints.length) {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i + 1]);
        } else {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i + 1]);
            baseURL = baseURL.concat("+");
        }
    }

    // TIME
    baseURL = baseURL.concat("&lat1=&lon1=&lat2=&lon2=&resolutionSub=&listLat1=&listLon1=&listLat2=&listLon2=&resolutionList=&endPoint1Lat=&endPoint1Lon=&endPoint2Lat=&endPoint2Lon=&listEndPoint1Lat=&listEndPoint1Lon=&listEndPoint2Lat=&listEndPoint2Lon=&zipCodeList=&listZipCodeList=&centerPointLat=&centerPointLon=&distanceLat=&distanceLon=&resolutionSquare=&listCenterPointLat=&listCenterPointLon=&listDistanceLat=&listDistanceLon=&listResolutionSquare=&citiesLevel=&listCitiesLevel=&sector=&gmlListLatLon=&featureType=&requestedTime=&startTime=&endTime=&compType=&propertyName=&product=time-series&begin=2016-09-04T00:00:00&end=2016-09-11T00:00:00");

    // CHARACTERISTICS REQUESTED
    // http://graphical.weather.gov/xml/docs/elementInputNames.php
    baseURL = baseURL.concat("&Unit=e&maxt=maxt&mint=mint&temp=temp&appt=appt&rh=rh&sky=sky&wwa=wwa&iceaccum=iceaccum&ptornado=ptornado&phail=phail&ptstmwinds=ptstmwinds&pxtornado=pxtornado&pxhail=pxhail&ptotsvrtstm=ptotsvrtstm&wgust=wgust");

    // Used for testing and seeing the final result
    console.log(baseURL);
    //retun to callback after getting URL
    next(null, baseURL)
}

答案 1 :(得分:0)

这不是回调如何运作。将处理程序更改为以下内容:

exports.handler = (event, context, callback) => {
  var arrayOfPoints = [39.7683800, -86.1580400, 41.881832, -87.623177];
  getXMLFromNOAA(arrayOfPoints, function(result) {
    console.log('returned');
    console.log(result);
    callback(null, result);
  });
};

同时取消注释(返回)callback(result)中的getXMLFromNOAA;

对于NOAA,还有一个模块。在重新发明轮子之前,始终首先搜索node-modules / npmjs.com / npms.io。这里的例子https://github.com/thataustin/noaa-forecasts与你正在做的非常相似所以我会从那开始。

如果您希望以后简化异步内容,可以将babelasyncawait关键字结合使用。但是你需要确保首先真正学习回调和承诺。