2017-08-01 39 views
-2

我想異步運行我的功能,但我怎麼做到這一點?:如何在Typescript中異步運行函數?

checkLocation() { 
     return __awaiter(this, void 0, Promise, function*() { 
      while (true) { 
       setTimeout(function() { 
        this.diagnostic.isLocationEnabled().then(
         (isAvailable) => { 
          console.log('Is available? ' + isAvailable); 
          if (!isAvailable) { 
           alert('Please turn on the location service'); 
          } 
         }).catch((e) => { 
          console.log(e); 
         }); 
       }, 5000) 
      } 
     }); 
    } 
} 

其中一個發現的問題是,TS不能罰款名__awaiter。我試圖按照this

+2

我們無法知道爲什麼'__awaiter'在問題中的代碼中不可用。它與sync/async沒有任何關係。 –

+0

我只是試圖按照我發佈的鏈接。這就是爲什麼我問你們:) –

+1

'__awaiter'不是你**寫的東西。如果你使用'async' /'await'函數,它由TypeScript編譯器輸出。來自你的鏈接:*「對於上面的示例,TypeScript編譯器爲'ping'函數發出了下面的ES6 JavaScript。」*這很清楚地表明,包含'__awaiter'的代碼是TypeScript編譯器的**輸出** 。 –

回答

0

正如我在評論中所說的,__awaiter不是寫的。如果您使用我們的async/await函數,它由TypeScript編譯器輸出。

回覆你說你想做的事:

[它]應檢查位置服務(電話)是異步啓用

的檢查將是異步不管,因爲this.diagnostic.isLocationEnabled是異步的。

checkLocation將使它成爲async方法,這將消耗經由awaitisLocationEnabled承諾的async/await方式:

async checkLocation() { 
    const isAvailable = await this.diagnostic.isLocationEnabled(); 
    console.log('Is available? ' + isAvailable); 
    if (!isAvailable) { 
     alert('Please turn on the location service'); 
    } 
    return isAvailable; 
} 

非易失async/await版本的,它是此使用承諾明確:

checkLocation() { 
    return this.diagnostic.isLocationEnabled().then(isAvailable => { 
     console.log('Is available? ' + isAvailable); 
     if (!isAvailable) { 
      alert('Please turn on the location service'); 
     } 
     return isAvailable; 
    }); 
} 

請注意,我已經刪除了catch處理呃,因爲通過返回承諾,你將錯誤處理推遲給調用者。

如果checkLocation是爲了防火而不是返回標誌的(承諾),那麼您根本不會使用async函數,也不會返回承諾(並且保留catch):

checkLocation() { 
    this.diagnostic.isLocationEnabled().then(isAvailable => { 
     console.log('Is available? ' + isAvailable); 
     if (!isAvailable) { 
      alert('Please turn on the location service'); 
     } 
    }).catch((e) => { 
     console.log(e); 
    }); 
} 
+0

這將是你的最後一個建議。然而,如果我想讓它繼續運行,我不能在'this.diagnostic.isLocationEnabled()之前放置一個while循環。然後(isAvailable => {'? –

+0

@GeorgeW:你的意思是「保持運行」?希望你的意思並不是說你要不斷提醒用戶? –

+0

我的意思是,只要'isAvailable'是假的,它就會一直顯示警報。當應用程序需要用戶位置才能正常工作時,需要它。 –

相關問題