[英]Stuck on trying to understand how Promises in JS worked
我正在開發移動應用程序,使用 Ionic 4 和 Angular 8。我遇到了一些麻煩,試圖實現簡單的任務。
所以,我在 Angular 服務中使用: @ionic-native/native-storage & @angular/http ,如下所示:
async getToken() {
await this.storage.getItem('token')
.then((res) => {
this.token = res
})
}
這是一個 Promise 解析函數,對嗎?
然后,我需要在另一個函數中調用這個 async/await 函數:
latest() {
this.getToken()
let options = {
headers: new HttpHeaders({
'Auth-Key': this.token
})
}
return this.http.get(this.env.API_URL + 'url', options)
}
下一步是從頁面調用服務功能:
getLatestVideo() {
this.videoService.latest()
.subscribe(data => {
this.latestVideo = data;
})
}
現在的問題是:
當我嘗試獲取此令牌時,從存儲中獲取“令牌”的函數未完成,Promise 未解析。
因此,當我調用 HttpClient 並嘗試從 api 獲取一些數據時,我收到一條錯誤消息,內容為:“令牌,您嘗試調用的是 null”。
有人可以解釋 Promises 是如何工作的嗎? 我無法得到它
更新1:
問題通過 2 個步驟解決:第 1 步:使 latest() 異步
async latest() {
await this.getToken()
let options = {
headers: new HttpHeaders({
'Auth-Key': this.token
})
}
return this.http.get(this.env.API_URL + 'url', options)
}
第 2 步:也使 getLatestVideo() 異步
async getLatestVideo() {
const latestVideo = await this.videoService.latest();
latestVideo.subscribe(data => {
this.latestVideo = data;
})
}
新問題:如何在視圖內解決所有承諾后顯示數據:
<div *ngFor="let video of latestVideo">{{ video.id }}</div>
好的,你必須使用更多的等待。
async latest() {
await this.getToken()
let options = {
headers: new HttpHeaders({
'Auth-Key': this.token
})
}
return this.http.get(this.env.API_URL + 'url', options)
}
下一步
async getLatestVideo() {
const latestVideo = await this.videoService.latest();
latestVideo.subscribe(data => {
this.latestVideo = data;
})
}
也許這會有所幫助?
getToken(): Observable<string> {
return from(this.storage.getItem('token'));
}
latest() {
return this.getToken().pipe(
switchMap(token => {
const headers = new HttpHeaders({ auth: token });
return this.http.get(this.env.API_URL + 'video', { headers });
}),
)
}
您可以返回承諾,而不是讓所有函數都異步等待。 例如getToken() { return this.storage.getItem('token') }
然后在最新的你可以簡單地擁有:
const token = await this.getToken()
let options = {
headers: new HttpHeaders({
'Auth-Key': token
})
}
return this.http.get(this.env.API_URL + 'url', options)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.