How to return value from an asynchronous callback function?

This question already has an answer here:

  • How do I return the response from an asynchronous call? 33 answers

  • 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 makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.

    Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.


    If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/

    It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.

    链接地址: http://www.djcxy.com/p/5790.html

    上一篇: 音频回调功能有时不被调用

    下一篇: 如何从异步回调函数中返回值?