2017-03-02 41 views
3

我不知道是否有可能将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) 
    } 
    } 
} 
+0

类似[Observables提案](https://github.com/tc39/proposal-observable/blob/master/README.md)? – gyre

+0

这个*可以完成,但承诺是需要发生一次的事情的理想选择。听众模型 - 比如Observable - 会更加明显。 – lonesomeday

回答

0

还没有。

您描述的模式是Observable - Javascript中没有语言支持,但它即将推出。

在ES2015我们得到了发电机:function* & yield,这使得迭代 - 拉各yieldfor ... of循环。

发电机也支持推观察员,与var valToGet = yield foo;generator.next(valToPush);语法。

发电机是同步的 - 它们只是来回传递一个线程。

在ES2017我们得到了async & await - 在幕后这些用发电机给每个await转换在async functionyield new Promise(...async function变成迭代器承诺

理想的情况下,我们将能够做这样的事情:

async watchPosition*() { 
    try { 
     while(this.enabled) { 
      // Loop each time navigator.geolocation.watchPosition fires success 
      const position = await this.watchCurrentPosition(); 

      // Pass back to the listener until generator.next 
      const atDestination = yield position; 
      if(atDestination) 
       break; // We're here, stop watching 
     } 
    } 
    catch (error) { 
     console.log(error) 
    } 
} 

不幸的是,async function*尚不支持 - 功能,可生成或async,但不能同时使用。目前也没有漂亮的for ... of语法像有对迭代器,只是笨重generator.next(pushValue),所以消耗这个假设的方法是有点丑:

async listener() { 
    const generator = Geo.watchPosition(); 
    let item = await generator.next(false); 
    while (!item.done) { 
     // Update UI 
     const atDestination = areWeThereYet(item.value); 
     item = await generator.next(atDestination); 
    } 
} 

所以异步迭代器/观测值都来了,但有很多东西需要先解决。

与此同时,有一些例外的库支持观察者模式,并且现在可用,例如RxJS

相关问题