自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

盤點(diǎn)JavaScript中的Promise鏈的高級(jí)用法

開發(fā) 前端
本文基于JavaScript基礎(chǔ),介紹了Promise 鏈的高級(jí)用法,主要介紹了使用Promise時(shí)新手常會(huì)出現(xiàn)的幾個(gè)問題,對(duì)這幾個(gè)問題進(jìn)行詳細(xì)的解答。

[[416503]]

大家好,我進(jìn)階學(xué)習(xí)者。

一、前言

有一系列的異步任務(wù)要一個(gè)接一個(gè)地執(zhí)行 — 例如,加載腳本。如何寫出更好的代碼呢?

Promise 提供了一些方案來(lái)做到這一點(diǎn)。

二、案例分析

1.運(yùn)行流程如下

它的理念是將 result 通過 .then 處理程序(handler)鏈進(jìn)行傳遞。

  1. //1. 初始 promise 在 1 秒后進(jìn)行 resolve (*), 
  2.  
  3. //2. 然后 .then 處理程序(handler)被調(diào)用 (**)。 
  4.  
  5. //3. 它返回的值被傳入下一個(gè) .then 處理程序(handler)(***)。 

之所以這么運(yùn)行,是因?yàn)閷?duì) promise.then 的調(diào)用會(huì)返回了一個(gè) promise,所以可以在其之上調(diào)用下一個(gè) .then。

當(dāng)處理程序(handler)返回一個(gè)值時(shí),它將成為該 promise 的 result,所以將使用它調(diào)用下一個(gè) .then。

新手常犯的一個(gè)經(jīng)典錯(cuò)誤:從技術(shù)上講,也可以將多個(gè) .then 添加到一個(gè) promise 上。但這并不是 promise 鏈(chaining)。

例 :

  1. let promise = new Promise(function(resolve, reject) { 
  2.   setTimeout(() => resolve(1), 1000); 
  3. }); 
  4. promise.then(function(result) { 
  5.   alert(result); // 1 
  6.   return result * 2; 
  7. }); 
  8. promise.then(function(result) { 
  9.   alert(result); // 1 
  10.   return result * 2; 
  11. }); 
  12. promise.then(function(result) { 
  13.   alert(result); // 1 
  14.   return result * 2; 
  15. }); 

在這里所做的只是一個(gè) promise 的幾個(gè)處理程序(handler)。他們不會(huì)相互傳遞 result;相反,它們之間彼此獨(dú)立運(yùn)行處理任務(wù)。

例1:fetch

在前端編程中,promise 通常被用于網(wǎng)絡(luò)請(qǐng)求。

案例:

將使用 [etch方法從遠(yuǎn)程服務(wù)器加載用戶信息。它有很多可選的參數(shù)。

  1. let promise = fetch(url); 

執(zhí)行這條語(yǔ)句,向 url 發(fā)出網(wǎng)絡(luò)請(qǐng)求并返回一個(gè) promise。當(dāng)遠(yuǎn)程服務(wù)器返回 header(是在 全部響應(yīng)加載完成前)時(shí),該 promise 用使用一個(gè) response 對(duì)象來(lái)進(jìn)行 resolve。

為了讀取完整的響應(yīng),應(yīng)該調(diào)用 response.text() 方法:當(dāng)全部文字(full text)內(nèi)容從遠(yuǎn)程服務(wù)器下載完成后,它會(huì)返回一個(gè) promise,該 promise 以剛剛下載完成的這個(gè)文本作為 result 進(jìn)行 resolve。

下面這段代碼向 user.json 發(fā)送請(qǐng)求,并從服務(wù)器加載該文本:

  1. fetch('/article/promise-chaining/user.json'
  2.   // 當(dāng)遠(yuǎn)程服務(wù)器響應(yīng)時(shí),下面的 .then 開始執(zhí)行 
  3.   .then(function(response) { 
  4.     // 當(dāng) user.json 加載完成時(shí),response.text() 會(huì)返回一個(gè)新的 promise 
  5.     // 該 promise 以加載的 user.json 為 result 進(jìn)行 resolve 
  6.     return response.text(); 
  7.   }) 
  8.   .then(function(text) { 
  9.     // ...這是遠(yuǎn)程文件的內(nèi)容 
  10.     alert(text); // {"name""iliakan""isAdmin"true
  11.   }); 

從 fetch 返回的 response 對(duì)象還包括 response.json() 方法,該方法讀取遠(yuǎn)程數(shù)據(jù)并將其解析為 JSON。在的例子中,這更加方便,所以讓切換到這個(gè)方法。

為了簡(jiǎn)潔,還將使用箭頭函數(shù):

  1. // 同上,但是使用 response.json() 將遠(yuǎn)程內(nèi)容解析為 JSON 
  2. fetch('/article/promise-chaining/user.json'
  3.   .then(response => response.json()) 
  4.   .then(user => alert(user.name)); // iliakan, got user name 

現(xiàn)在,讓用加載好的用戶信息搞點(diǎn)事情。

例如,可以多發(fā)一個(gè)到 GitHub 的請(qǐng)求,加載用戶個(gè)人資料并顯示頭像:

  1. // 發(fā)送一個(gè)對(duì) user.json 的請(qǐng)求 
  2. fetch('/article/promise-chaining/user.json'
  3.   // 將其加載為 JSON 
  4.   .then(response => response.json()) 
  5.   // 發(fā)送一個(gè)到 GitHub 的請(qǐng)求 
  6.   .then(user => fetch(`https://api.github.com/users/${user.name}`)) 
  7.   // 將響應(yīng)加載為 JSON 
  8.   .then(response => response.json()) 
  9.   // 顯示頭像圖片(githubUser.avatar_url)3 秒(也可以加上動(dòng)畫效果) 
  10.   .then(githubUser => { 
  11.     let img = document.createElement('img'); 
  12.     img.src = githubUser.avatar_url; 
  13.     img.className = "promise-avatar-example"
  14.     document.body.append(img); 
  15.     setTimeout(() => img.remove(), 3000); // (*) 
  16.   }); 

這段代碼可以工作,具體細(xì)節(jié)請(qǐng)看注釋。但是,這兒有一個(gè)潛在的問題,一個(gè)新手使用 promise 的典型問題。

請(qǐng)看 (*) 行:如何能在頭像顯示結(jié)束并被移除 之后 做點(diǎn)什么?例如,想顯示一個(gè)用于編輯該用戶或者其他內(nèi)容的表單。就目前而言,是做不到的。

為了使鏈可擴(kuò)展,需要返回一個(gè)在頭像顯示結(jié)束時(shí)進(jìn)行 resolve 的 promise。

就像這樣:

  1. fetch('/article/promise-chaining/user.json'
  2.   .then(response => response.json()) 
  3.   .then(user => fetch(`https://api.github.com/users/${user.name}`)) 
  4.   .then(response => response.json()) 
  5.   .then(githubUser => new Promise(function(resolve, reject) { // (*) 
  6.     let img = document.createElement('img'); 
  7.     img.src = githubUser.avatar_url; 
  8.     img.className = "promise-avatar-example"
  9.     document.body.append(img); 
  10.     setTimeout(() => { 
  11.       img.remove(); 
  12.       resolve(githubUser); // (**) 
  13.     }, 3000); 
  14.   })) 
  15.   // 3 秒后觸發(fā) 
  16.   .then(githubUser => alert(`Finished showing ${githubUser.name}`)); 

注:

也就是說,第 (*) 行的 .then 處理程序(handler)現(xiàn)在返回一個(gè) new Promise,只有在 setTimeout 中的 resolve(githubUser) (**) 被調(diào)用后才會(huì)變?yōu)?settled。鏈中的下一個(gè) .then 將一直等待這一時(shí)刻的到來(lái)。

作為一個(gè)好的做法,異步行為應(yīng)該始終返回一個(gè) promise。這樣就可以使得之后計(jì)劃后續(xù)的行為成為可能。即使現(xiàn)在不打算對(duì)鏈進(jìn)行擴(kuò)展,但之后可能會(huì)需要。

三、總結(jié)

本文基于JavaScript基礎(chǔ),介紹了Promise 鏈的高級(jí)用法,主要介紹了使用Promise時(shí)新手常會(huì)出現(xiàn)的幾個(gè)問題,對(duì)這幾個(gè)問題進(jìn)行詳細(xì)的解答。

通過案例的分析,能夠更直觀的展示。采用JavaScript語(yǔ)言,能夠幫助你更好的學(xué)習(xí)JavaScript。

代碼很簡(jiǎn)單。希望能夠幫助你更好的學(xué)習(xí)。

 

責(zé)任編輯:姜華 來(lái)源: 前端進(jìn)階學(xué)習(xí)交流
相關(guān)推薦

2024-08-13 15:23:37

2015-07-23 11:59:27

JavascriptPromise

2022-07-03 08:06:40

JavaScript語(yǔ)言代碼

2021-02-07 22:59:55

JavaScript編程方法鏈

2021-09-04 07:56:44

Pythonos模塊

2011-05-25 14:23:55

Javascriptthis

2023-09-15 15:31:23

異步編程Promise

2009-06-17 15:01:07

javascript

2021-10-09 07:10:30

JavaScriptBigIn函數(shù)

2021-10-09 07:10:31

JavaScript對(duì)象Python

2017-03-10 10:16:37

PythonRequests庫(kù)

2021-06-07 09:44:10

JavaScript開發(fā)代碼

2022-04-04 09:12:18

Python內(nèi)置函數(shù)

2022-10-11 23:50:43

JavaScript編程Promise

2011-05-12 18:26:08

Javascript作用域

2021-06-15 10:01:27

JavaScript數(shù)組遍歷Entries

2021-09-14 07:26:25

JavaScript迭代對(duì)象

2021-08-31 10:01:04

JavaScript函數(shù)屬性

2021-09-03 10:00:00

JavaScript迭代對(duì)象

2025-03-26 10:56:54

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)