JS - Promise + geolocation.watchPosition

时间:2014-05-29 20:26:35

标签: javascript geolocation promise

我正在尝试将JavaScript Promise与地理定位一起使用,但无法使其与 geolocation.watchPosition 一起正常工作, then 子句只被调用一次:

function Geolocation() {
  this._options = {
    enableHighAccuracy: true, 
    maximumAge        : 10000, 
    timeout           : 7000
  }
}

Geolocation.prototype = {
  get watchID() { return this._watchID; },
  set watchID(watchID) { this._watchID = watchID; },
  get options() { return this._options; },
  // hasCapability: function() { return "geolocation" in navigator; },
  _promise: function(promise) {
    var geolocation = this;
    if (promise == "getPosition")
      return new Promise(function(ok, err) {
        navigator.geolocation.getCurrentPosition(
          ok.bind(geolocation), err.bind(geolocation),
          geolocation.options
        );
      });
    else if (promise == "watchPosition")
      return new Promise(function(ok, err) {
        geolocation.watchID = navigator.geolocation.watchPosition(
          ok.bind(geolocation), err.bind(geolocation),
          geolocation.options
        );
      });
  },
  getPosition: function() { return this._promise('getPosition'); },
  watchPosition: function() {
    this.clearWatch();
    return this._promise('watchPosition');
  },
  clearWatch: function() {
    if (!this.watchID) return;
    navigator.geolocation.clearWatch(this.watchID);
    this.watchID = null;
  }
};

var geolocation = new Geolocation();
geolocation.watchPosition()
  .then(
    function(position) {
      console.log("latitude: " + position.coords.latitude + " - longitude: " + position.coords.longitude)
    },
    function(error) {
      console.log("error: " + error);
    }
  )

我尝试使用 watchPosition / 0 返回的中间承诺,但它返回相同的结果。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

回答自己。

关于使用回调的@Benjamin Gruenbaum建议,可以将处理geolocation.watchPosition响应的单个回调与Promise相结合,然后使用then().catch()模式({ {1}}功能):

notify

不确定我是否正确使用Promise,但它可以正常工作并允许利用链接。

答案 1 :(得分:1)

我发现 Zach Leatherman

这个惊人的帖子
function getCurrentPositionDeferred(options) {
  var deferred = $.Deferred();
  navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject, options);
  return deferred.promise();
};

这使我们可以执行以下操作:

getCurrentPositionDeferred({
  enableHighAccuracy: true
}).done(function() {
  // success
}).fail(function() {
  // failure
}).always(function() {
  // executes no matter what happens.
  // I've used this to hide loading messages.
});
// You can add an arbitrary number of
// callbacks using done, fail, or always.

要在多个Deferred对象之间进行协调,请使用$ .when:

$.when(getCurrentPositionDeferred(), $.ajax("/someUrl")).done(function() {
  // both the ajax call and the geolocation call have finished successfully.
});

来源:http://www.zachleat.com/web/deferred-geolocation/