2017-03-02 42 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

相關問題