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

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

问题描述

这个问题是在SO问了很多次。但我仍然无法得到的东西。

我想从回调一定的价值。看看下面澄清脚本。

 函数foo(地址){      //谷歌地图的东西
      地理coder.geo code({'地址':地址},功能(结果状态){
          结果[0] .geometry.location; //我想返回该值
      })    }
    富(); //结果应该是结果[0] .geometry.location;值

如果我试图返回值刚开不确定。我跟着从这么一些想法,但
仍然失败。

这些是:

 函数foo(地址){
    VAR返回值;
    地理coder.geo code({'地址':地址},功能(结果状态){
        返回值=结果[0] .geometry.location;
    })
    返回返回值;
}
富(); //仍然不确定


解决方案

这是不可能的,因为你不能从一个异步调用同步方法中返回。

在这种情况下,你需要通过回调来富将接收返回值

 函数foo(地址,FN){
  地理coder.geo code({'地址':地址},功能(结果状态){
     FN(结果[0] .geometry.location);
  });
}富(地址功能(位置){
  警报(位置); //这是你在哪里得到的返回值
});

问题是,如果一个内部函数调用是异步的,那么所有的功能包裹这一呼吁也必须按顺序异步回归的回应。

如果你有很多的回调可以考虑冒险尝试和使用承诺图书馆像:Q

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

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

Those are:

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

解决方案

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

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.

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

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

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