日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

angular routerlink传递参数_[翻译]在 Angular 中使用 async-await 特性

發(fā)布時(shí)間:2024/9/15 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 angular routerlink传递参数_[翻译]在 Angular 中使用 async-await 特性 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

在 Angular 中使用 async-await 特性

原文鏈接:

https://medium.com/@balramchavan/using-async-await-feature-in-angular-587dd56fdc77?medium.com更新:在Angular的新版本中,我們不需要擔(dān)心 http()[1] 返回的 promise。盡管如此,我們?nèi)匀豢梢允褂?async-await 來實(shí)現(xiàn)其他基于 promise 的邏輯。

在 JavaScript 中,用 Promises 和回調(diào)函數(shù)編寫異步代碼。

在 Angular 應(yīng)用中,我們可以使用 Rx.js 利用 Observables, Subject, BehaviorSubject 等強(qiáng)大的功能,以優(yōu)雅的方式編寫異步代碼。

ECMA 腳本草案的最新版本,JavaScript 開始支持 async-await。

ECMAScript Latest Draft (ECMA-262)

如果你有 c# 的開發(fā)背景,你可能知道從 c# 5開始就支持 async-await 特性了。

Async-await

按照MDN

當(dāng)調(diào)用異步函數(shù)時(shí),它返回一個(gè) Promise 。當(dāng) async 函數(shù)返回一個(gè)值時(shí),將使用返回的值 resolved Promise。當(dāng)異步函數(shù)拋出異常或某個(gè)值時(shí),將使用拋出的值 rejected promise。 異步函數(shù)可以包含一個(gè) await 表達(dá)式,該表達(dá)式掛起異步函數(shù)的執(zhí)行并等待傳遞的 Promise 的解析,然后恢復(fù)異步函數(shù)的執(zhí)行并返回 resolved 后的值。

簡單地說,您將有機(jī)會(huì)以同步方式編寫異步代碼。

例1

讓我們考慮一個(gè)簡單的例子。一個(gè)函數(shù),它在兩秒后返回一個(gè)承諾解析并返回作為參數(shù)傳遞的值。

resolveAfter2Seconds(x) {return new Promise(resolve => {setTimeout(() => {resolve(x);}, 2000);});}

使用 promise ,我們可以使用 then 回調(diào)函數(shù)獲得值。

getValueWithPromise() {this.resolveAfter2Seconds(20).then(value => {console.log(`promise result: ${value}`);});console.log('I will not wait until promise is resolved'); }

在上述情況下,第5行 console.log() 應(yīng)在第3行 console.log() 之前執(zhí)行。這是Promise的基礎(chǔ)能力。

現(xiàn)在,我們看下 async-await 的用法

async getValueWithAsync() {const value = <number>await this.resolveAfter2Seconds(20);console.log(`async result: ${value}`);}

這里有幾點(diǎn)需要注意:

第1行-函數(shù)的前綴是 async 關(guān)鍵字。如果函數(shù)有 wait 關(guān)鍵字,則必須使用此前綴。

第2行-我們沒有在 promise 函數(shù)之后調(diào)用 .then() 回調(diào)函數(shù)。相反,我們用 await 關(guān)鍵字作為函數(shù)調(diào)用的前綴。此關(guān)鍵字不允許執(zhí)行下一個(gè)代碼塊。這意味著,只有當(dāng) promise 像同步函數(shù)調(diào)用一樣在第2行解析時(shí),第3行的 console.log() 才會(huì)被打印出來。

由于我們使用 Typescript,所以需要將 promise 返回值轉(zhuǎn)成特定類型,因此轉(zhuǎn)成第2行的類型。

例2

讓我們嘗試使用基于 promise 的方法添加兩個(gè)數(shù)字。

addWithPromise() {this.resolveAfter2Seconds(20).then(data1 => {let result1 = <number>data1;this.resolveAfter2Seconds(30).then(data2 => {let result2 = <number>data2;this.additionPromiseResult = result1 + result2;console.log(`promise result: ${this.additionPromiseResult}`);});});}

在實(shí)際應(yīng)用程序中,很常見的情況是最后出現(xiàn)嵌套的 promise-then 結(jié)構(gòu)(回調(diào)地獄)。我們上面的代碼就出現(xiàn)了2級嵌套。想象一下用捕獲的變量和異常(如果有的話)進(jìn)行7-8級嵌套。可怕的不是嗎?

現(xiàn)在我們使用基于 async 的方法

async addWithAsync() {const result1 = <number>await this.resolveAfter2Seconds(20);const result2 = <number>await this.resolveAfter2Seconds(30);this.additionAsyncResult = result1 + result2;console.log(`async result: ${this.additionAsyncResult}`);}

比較一下代碼的簡潔性。這兩種方法將給我們相同的結(jié)果,但在代碼可讀性方面,維護(hù) async-await 優(yōu)于經(jīng)典的 promise-then 方法。

消費(fèi)Http REST APIs

到目前為止,我們討論了一些簡單的例子。在 Angular 應(yīng)用中,我們可以使用 Http[2] (即將過時(shí))或 HttpClient 服務(wù)來獲取 REST 數(shù)據(jù)。默認(rèn)情況下,HttpClient 類的 get() 、 put() 、 delete() 和 post() 方法返回 Observable<T> 。這個(gè)結(jié)果集可以通過 subscribe 方法或使用 RxJs 中的 toPromise() 操作符來使用。

使用 Observable 獲取 HttpClient 結(jié)果:

我見過很多 Angular 開發(fā)人員使用 subscribe 來獲取 Http REST 數(shù)據(jù),卻不知道它與 promise 的區(qū)別。 subscribe 方法來自 Observable 對象。一旦訂閱,subscribe 回調(diào)將在 Observer 產(chǎn)生新數(shù)據(jù)時(shí)執(zhí)行。而 promise 的 then() 回調(diào)處理器最多只能執(zhí)行一次。因此,除非您需要使用重復(fù)數(shù)據(jù),否則不要使用 subscribe 。使用 toPromise () 。如果你注意到 Angular 官方文檔中給出的例子; toPromise 有很多用法。

getDataUsingSubscribe() {this.httpClient.get<Employee>(this.url).subscribe(data => {this.subscribeResult = data;console.log('Subscribe executed.')});console.log('I will not wait until subscribe is executed..');}

使用 toPromise 獲取 HttpClient 結(jié)果

Rx.js 提供了一個(gè)名為 toPromise() 的操作符,可以將 Observeble<T> 轉(zhuǎn)換成 promise。一旦轉(zhuǎn)換后,它的 then 塊每當(dāng)方法產(chǎn)生數(shù)據(jù)時(shí)會(huì)被調(diào)用執(zhí)行。

getDataUsingPromise() {this.httpClient.get<Employee>(this.url).toPromise().then(data => {this.promiseResult = data;console.log('Promise resolved.')});console.log('I will not wait until promise is resolved..');}

使用 async-await 獲得 HttpClient 結(jié)果:

使用 async-await 模式,我們既不需要 subscribe 也不需要 toPromise 。代碼看起來非常簡單和直接。從 url 獲取數(shù)據(jù)后,執(zhí)行第3行,將 Observerable 轉(zhuǎn)換為 promise,并解析promise,數(shù)據(jù)存儲(chǔ)在 asyncResult 成員變量中。

async getAsyncData() {this.asyncResult = await this.httpClient.get<Employee>(this.url).toPromise();console.log('No issues, I will wait until promise is resolved..');}

有條件的編程

很多時(shí)候,應(yīng)用程序需要從一個(gè)url獲取數(shù)據(jù),并根據(jù)條件來獲取下一個(gè)數(shù)據(jù)。使用 promise 代碼應(yīng)該是這樣的:

getConditionalDataUsingPromise() {this.httpClient.get<Employee>(this.url).toPromise().then(data => {console.log('First Promise resolved.')if (data.id > 5) {let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';this.httpClient.get<Employee>(anotherUrl).toPromise().then(data => {this.conditionalPromiseResult = data;console.log('Second Promise resolved.')});}});}

使用 async-await 代碼是這樣的:

async getConditionalDataUsingAsync() {let data = await this.httpClient.get<Employee>(this.url).toPromise();if (data.id > 5) {let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';this.conditionalAsyncResult = await this.httpClient.get<Employee>(anotherUrl).toPromise();}console.log('No issues, I will wait until promise is resolved..');}

源代碼

你可以從我們的 GitHub 倉庫獲取完整代碼

ultrasonicsoft/ng-async-await-demo?github.com

總結(jié)

總之,async-await 特性為我們在 Angular 應(yīng)用程序中編寫異步代碼提供了更好的方法。

參考

  • ^譯者注:8.0已經(jīng)完全移除@angular/http
  • ^已過時(shí)
  • 總結(jié)

    以上是生活随笔為你收集整理的angular routerlink传递参数_[翻译]在 Angular 中使用 async-await 特性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。