如何从嵌套的匿名函数返回值父函数 [英] how to return value to parent function from nested anonymous function

查看:166
本文介绍了如何从嵌套的匿名函数返回值父函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript函数应返回地址解析为一个字符串:

I have a javascript function which should return a geocoding for a string:

    function codeAddress(address) {
    var result = (new google.maps.Geocoder()).geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        return String(results[0].geometry.location.Ya)+','+String(results[0].geometry.location.Za)
      } else {
        return status;
      }
    });
    console.log(result);
    return result
}

然而,它返回未定义。我理解的错误在这里,也就是说,因为JavaScript是异步的,它从函数返回 codeAddress 之前甚至功能(结果状态)得到充分执行。但我需要知道什么是这里的解决方案和最佳实践。

However it returns "undefined". I understand the bug here,i.e, since javascript is asynchronous, its returning from the function codeAddress even before function(results, status) gets fully executed. But I need to know whats the solution here and the best practice.

推荐答案

由于它是异步的,你应该通过它处理函数的回调:

Since it's asynchronous, you should pass a callback which handles the function:

function codeAddress(address, callback) {
    (new google.maps.Geocoder()).geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(String(results[0].geometry.location.Ya) + ','
                    + String(results[0].geometry.location.Za))
        } else {
            callback(status);
        }
    });
}

codeAddress("test", function(result) {
    // do stuff with result
});

如果你正在使用jQuery,你也可以使用延迟:

If you're using jQuery, you could also use deferred:

function codeAddress(address, callback) {
    var dfd = new jQuery.Deferred();

    (new google.maps.Geocoder()).geocode({
        'address' : address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
             // trigger success
            dfd.resolve(String(results[0].geometry.location.Ya) + ','
                    + String(results[0].geometry.location.Za));
        } else {
            // trigger failure
            dfd.reject(status); 
        }
    });

    return dfd;
}

codeAddress("some address").then(
    // success
    function(result) {
        // do stuff with result
    },
    // failure
    function(statusCode) {
        // handle failure
    }
);

这篇关于如何从嵌套的匿名函数返回值父函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆