如何从异步回调函数返回值? [英] How to return value from an asynchronous callback function?

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

问题描述

这个问题在SO中被问过很多次。但我还是不能得到东西。

This question is asked many times in SO. But still I can't get stuff.

我想从回调中得到一些值。看看下面的脚本澄清。

I want to get some value from callback. Look at the script below for clarification.

function foo(address){

      // google map stuff
      geocoder.geocode( { 'address': address}, function(results, status) {
          results[0].geometry.location; // I want to return this value
      })

    }
    foo(); //result should be results[0].geometry.location; value

如果我尝试返回该值,只是得到undefined。我跟着一些想法从SO,但
仍然失败。

If I try to return that value just getting "undefined". I followed some ideas from SO, but still fails.

这些是:

function foo(address){
    var returnvalue;    
    geocoder.geocode( { 'address': address}, function(results, status) {
        returnvalue = results[0].geometry.location; 
    })
    return returnvalue; 
}
foo(); //still undefined


推荐答案

在这种情况下,您需要向foo传递一个回调,该回调将接收返回值

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {
     fn(results[0].geometry.location); 
  });
}

foo("address", function(location){
  alert(location); // this is where you get the return value
});

事情是,如果内部函数调用是异步的,那么所有的函数'必须也是异步的,以便返回响应。

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

如果你有很多回调,你可以考虑采取暴跌,并使用 promise库like Q

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

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

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