我不知道是否有可能將Geolocation.watchPosition()
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition包裝在承諾中,並將其與async/await
成語結合使用。每當設備的位置發生變化並調用後續功能時不斷返回位置。是否可以在Promise中封裝Geolocation.watchPosition()等函數?
// Example Class
class Geo {
// Wrap in Promise
getCurrentPosition(options) {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, options)
})
}
// Wrap in Promise
watchCurrentPosition(options) {
return new Promise((resolve, reject) => {
navigator.geolocation.watchPosition(resolve, reject, options)
})
}
// Works well.
async currentPosition() {
try {
let position = await this.getCurrentPosition()
// do something with position.
}
catch (error) {
console.log(error)
}
}
// Any way...?
async watchPosition() {
try {
let position = await this.watchCurrentPosition()
// do something with position whenever location changes.
// Invoking recursively do the job but doesn't feel right.
watchPosition()
}
catch (error) {
console.log(error)
}
}
}
類似[Observables提案](https://github.com/tc39/proposal-observable/blob/master/README.md)? – gyre
這個*可以完成,但承諾是需要發生一次的事情的理想選擇。聽衆模型 - 比如Observable - 會更加明顯。 – lonesomeday