20

コールバックの情報を含むオブジェクトを返す関数を作成しようとしています:

var geoloc;

var successful = function (position) {
    geoloc = {
        longitude: position.coords.longitude,
        latitude: position.coords.latitude
    };
};

var getLocation = function () {
    navigator.geolocation.getCurrentPosition(successful, function () {
        alert("fail");
    });

    return geoloc;
};

これどうやってするの?関数が実行されるgetLocation前に null 値を返しますsuccessful

ありがとう!

4

2 に答える 2

25

関数が非同期であるため、コールバックが使用されます。コールバックは、将来のある時点で実行されます。

したがって、getLocationコールバックがトリガーされる前に yes が返されます。それが非同期メソッドの仕組みです。

コールバックを待つことはできません。それは機能しません。getLocation完了すると実行される にコールバックを追加できます。

var getLocation = function(callback){
    navigator.geolocation.getCurrentPosition(function(pos){
        succesfull(pos);
        typeof callback === 'function' && callback(geoloc);
    }, function(){
        alert("fail");
    });
};

実行して戻り値を期待する代わりにvar x = getLocation()、次のように呼び出します。

getLocation(function(pos){
    console.log(pos.longitude, pos.latitude);
});
于 2012-07-31T19:26:38.927 に答える
20

Rocket's answer のアプローチをお勧めします。ただし、本当に必要な場合はgetLocation、jQuery 遅延オブジェクトを使用して、終了時に残りのコードをトリガーすることができます。これにより、 が提供するコールバックを使用するだけでなく、よりきめ細かい制御が可能になりますgetCurrentPosition

// create a new deferred object
var deferred = $.Deferred();

var success = function (position) {
    // resolve the deferred with your object as the data
    deferred.resolve({
        longitude: position.coords.longitude,
        latitude: position.coords.latitude
    });
};

var fail = function () {
    // reject the deferred with an error message
    deferred.reject('failed!');
};

var getLocation = function () {
    navigator.geolocation.getCurrentPosition(success, fail); 

    return deferred.promise(); // return a promise
};

// then you would use it like this:
getLocation().then(
    function (location) {
         // success, location is the object you passed to resolve
    }, 
    function (errorMessage) {
         // fail, errorMessage is the string you passed to reject
    }); 
于 2012-07-31T19:33:33.740 に答える