【发布时间】:2017-07-21 20:32:48
【问题描述】:
我想知道是否可以将 Geolocation.watchPosition() https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition 包装在 Promise 中,并将其与 async/await 习语一起使用,以使其发挥作用;每当设备的位置发生变化并调用后续函数时,都会不断返回位置。
// 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)
}
}
}
【问题讨论】:
-
这可以完成,但是对于需要发生一次的事情来说,promise 是理想的。监听器模型——比如 Observable——会更加明显。
标签: javascript geolocation async-await ecmascript-2017