简体   繁体   English

用Javascript返回值

[英]Returning values in Javascript

I have a (hopefully quite simple) Javascript problem. 我有一个(希望很简单)JavaScript问题。 I've search but found nothing that is really relevant to the problem. 我已经搜索过,但没有发现与问题真正相关的内容。

Basically I have a function (addToGlobe) that calls two other functions (codeAddressLat and codeAddressLng) as it runs. 基本上,我有一个函数(addToGlobe)在运行时会调用其他两个函数(codeAddressLat和codeAddressLng)。 The two called functions should both return a float value to the first function, which then uses them. 这两个被调用的函数都应将浮点值返回给第一个函数,然后该函数将使用它们。 The subfunctions definitely work correctly - I did a print statement to check that the "numfinal" variable in each has a value, and it does. 子功能肯定可以正常工作-我做了一个打印语句,检查每个子功能中的“ numfinal”变量是否都具有值,并且确实如此。

However, when I add print statements to the calling function (as commented in the code), it returns 'undefined'. 但是,当我将打印语句添加到调用函数中(如代码中的注释所示)时,它返回“未定义”。 Therefore, the problem seems to be when the numfinal value is returned. 因此,问题似乎出在返回numfinal值时。

Thanks :) 谢谢 :)

function addToGlobe(uname, uid, pmcity) {
    // Get lat & long of city
    var pmlat = codeAddressLat(pmcity);
    var pmlong = codeAddressLng(pmcity);

    log(pmlat);   // PROBLEM! Prints 'undefined'
    log(pmlong);  // PROBLEM! Prints 'undefined'

    // Rest of function removed to keep it simple
}

function codeAddressLat(inputcity) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);

    geocoder.geocode( { 'address': inputcity}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          var llsplit = new Array();

          bkresult = String(results[0].geometry.location);
          bkresult = bkresult.replace(/[\(\)]/g, "");
          llsplit = bkresult.split(',');

          numfinal = parseFloat(llsplit[0]);
          return numfinal;

      } else {
        log('<b><font color="#C40031">Geocode was not successful:</b> ' + status);
      }
    });
 }

  function codeAddressLng(inputcity) {
        // Basically the same function as above. Removed for simplicity
     }

codeAddressLat is not actually returning anything. codeAddressLat实际上没有返回任何内容。 The anonymous function it passes to geocoder.geocode is. 它传递给geocoder.geocode的匿名函数是。

Since geocoder.geocode is running asynchronously, codeAddressLat can't wait around for its answer. 由于geocoder.geocode是异步运行的,因此codeAddressLat无法等待其答案。 So codeAddressLat really can't return anything of value. 因此,codeAddressLat实际上无法返回任何有价值的东西。 Instead codeAddressLat needs to become asynchronous too. 相反,codeAddressLat也需要变得异步。 This is a common pattern in JavaScript. 这是JavaScript中的常见模式。

function addToGlobe(uname, uid, pmcity) {
     codeAddressLat(pmcity, function(pmlat) {
        // do something with pmlat
    });

    ...
}

function codeAddressLat(inputcity, callback) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);

    geocoder.geocode( { 'address': inputcity}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          var llsplit = new Array();

          bkresult = String(results[0].geometry.location);
          bkresult = bkresult.replace(/[\(\)]/g, "");
          llsplit = bkresult.split(',');

          numfinal = parseFloat(llsplit[0]);

          // instead of returning, call the callback with the result
          callback(numfinal);

      } else {
        log('<b><font color="#C40031">Geocode was not successful:</b> ' + status);
      }
    });
}

您没有return语句中codeAddressLat ,你有一个内部定义的回调函数内codeAddressLat

Your function codeAddressLat is not actually returning a value but calling function that you pass a callback function which is returning a value. 您的函数codeAddressLat实际上并没有返回值,而是调用了您传递了返回值的回调函数的函数。 You need to wait until the geocode operation is complete to retrieve the value of numfinal. 您需要等到地址解析操作完成后才能检索numfinal的值。

您的函数codeAddressLat根本不返回任何值,因此您未定义为输出。

The geocode request in the codeAddressLat method call and will not return the value to the caller. 在codeAddressLat方法调用中的地址解析请求,不会将值返回给调用者。 Your return is of a different scope. 您的退货范围有所不同。

Does this work? 这样行吗?

function codeAddressLat(inputcity) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);

    return geocoder.geocode( { 'address': inputcity}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          var llsplit = new Array();

          bkresult = String(results[0].geometry.location);
          bkresult = bkresult.replace(/[\(\)]/g, "");
          llsplit = bkresult.split(',');

          numfinal = parseFloat(llsplit[0]);
          return numfinal;

      } else {
        log('<b><font color="#C40031">Geocode was not successful:</b> ' + status);
      }
    });
 }

That geocoder.geocode function looks like it is asynchronous. geocoder.geocode函数看起来像是异步的。 Your codeAddressLat and codeAddressLng functions returns void before the geocoder.geocode function has got data back from the server. codeAddressLatcodeAddressLng的功能之前返回void geocoder.geocode功能已经得到了数据从服务器返回。

A way to get around it is to nest your calls to geocoder.geocode and use variable scoping so that when all the AJAX calls have returned you can call your addToGlobe function passing the two parameters you want. 要解决它的方法是窝您拨打geocoder.geocode和使用的变量范围,这样,当所有的AJAX调用已经返回,你可以叫你addToGlobe函数传递你想要的两个参数。

Something like this: 像这样:

codeAddressLatAndLong(pmcity);

function addToGlobe(pmlatlat, pmlatlong) {
    log(pmlat);   // PROBLEM! Prints 'undefined'
    log(pmlong);  // PROBLEM! Prints 'undefined'

    // Rest of function removed to keep it simple
}

function codeAddressLatAndLong(inputcity) {
    // stuff

    geocoder.geocode( { 'address': inputcity}, function(results, status) {
      // stuff goes here
      pmlat = parseFloat(llsplit[0]);
      geocoder.geocode({...}, function(results, status) {
         // more stuff
         pmlatlong = something;
         addToGlobe(pmlatlat, pmlatlong);
      });
    });
}

Welcome to the world of AJAX. 欢迎来到AJAX的世界。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM