未定义错误回调

时间:2016-01-26 19:32:41

标签: node.js asynchronous apigee

我是node.js的新手并且无法理解回调和async.parallel的概念。我正在尝试在APIGEE中运行下面的node.js代码。它给我一个错误,说回调没有定义。

var request = require('request');
var async = require('async');
var express = require('express');
var urlparse = require('url');
var util = require('util');
var app = express();
var merge= require('underscore');
var http = require('http'); 
var myJson;
var myJson1;
var address_ups;


function sendError(resp, code, msg) {
    var oa = { 'error' : msg };
    resp.writeHead(code, {'Content-Type' :'applicationjson'});
    resp.end(JSON.stringify(oa));
}


var svr = http.createServer(function(req, resp) {
    var parsed = urlparse.parse(req.url, true);
    var postalcode=parsed.query.postalcode;
    if (!parsed.query.postalcode) {
        sendError(resp, 400, 'Missing query parameter postalcode');
    } else {
        async.parallel([


         function ups(postalcode,callback) {
       request('URL1', function(err, result, body) {
        if (err) {
        sendError(resp, 400, 
              util.format('Error response %s from geocoding web service', err.message));
        //cb(err);
         return;
        }
        else
        {
  profile = JSON.parse(body);
        }  
       });
       callback(postalcode,profile);
            },


       function dhl(postalcode,profile,callback) {
       request('URL2', function (err, result, body) {
        if (err) {
        sendError(resp, 400, 
              util.format('Error response %s from elevation web service', err.message));

        callback(err);
        return;
        }
        else
        {
  profile1 = JSON.parse(body);
  var profile3={'ups':profile,'dhl':profile};
        }
       });
       callback(profile3);
            }
       ], function(err,profile3) {
    if (err) {
        resp.status(500).send('Ouch,We had a problem!');
        //throw err; //Or pass it on to an outer callback, log it or whatever suits your needs
    }else{
        //o={'UPS':UPS,'DHL':DHL};
        resp.writeHead(200, {'Content-Type' :'applicationjson'});
    resp.end(JSON.stringify(profile3));

    }
    //console.log('Both a and b are saved now');
     });

    }
    });


svr.listen(9000, function() {
    console.log('Node Mashup sample app is running on port 9000');
    });

请注意代码不干净。
请在Node.js中解释async.parallel和callbacks的概念。

1 个答案:

答案 0 :(得分:1)

检查第一个函数中的邮政编码类型,如下所示:

console.log(typeof postalcode); // function?

我希望它是功能。即回调函数。

对于 async.parallel ,您不应传递除回调之外的任何参数。并行功能同时执行,因此您无法将数据从一个传递到另一个!

即使你使用的东西确实采用了诸如 async.waterfall 之类的参数,第一个函数参数也只需要一个回调。

瀑布的典型用途

async.waterfall([
    function (callback) { callback(arg1);  },
    function (arg1, callback) { callback(); }],
    function (err) {});

并在 parallel

async.parallel([
    function ups (callback) {

        // happening at the same time so nothing to pass!
        callback();
    },
    function (callback) {
        callback(); //etc.
    }],
    function (err) {});

在你的情况下,你正在生成

  • 邮政编码在异步构造之外,所以您不需要传递它
  • 异步构造中的
  • 个人资料,因此必须使用系列或瀑布

即。 更改您的代码以执行以下操作

var postalcode = "12345"; // This is available globally
                          // inside waterfall functions
async.waterfall([
    function (callback) {
       // generate some new profile data ...

       request('URL1', function(err, result, body) {
           if (err) {
               sendError(resp, 400,
                   util.format('Error response %s from geocoding web service', err.message));
               callback(err); // errors are passed back first.
               return;
           } 

           // Return callback inside request function!
           profile = JSON.parse(body);

           // for next funciton null will be ignored, profile is taken as
           // first argument
           callback(null, profile);
       });          
    },
    function (profile, callback) {
        request('URL2', function (err, result, body) {
            if (err) {
                sendError(resp, 400,
                    util.format('Error response %s from elevation web service', err.message));

                // error so pass back non-null first argument.
                callback(err);
                return;
            } 

            profile1 = JSON.parse(body);
            var profile3={'ups':profile,'dhl':profile};

            // Again. callback inside request callback body.
            // null first because there is no error
            callback(null, profile3);   
        });

    }], 
   function (err, profile) { // etc


   })
相关问题