欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用?JavaScript?Promise?讀取?Github?用戶數(shù)據(jù)

 更新時(shí)間:2022年08月15日 15:18:17   作者:JerryWang_sap  
這篇文章主要介紹了使用JavaScript?Promise讀取Github用戶數(shù)據(jù),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下

代碼如下:

// Make a request for user.json
fetch('/article/promise-chaining/user.json')
  // Load it as json
  .then(response => response.json())
  // Make a request to GitHub
  .then(user => fetch(`https://api.github.com/users/${user.name}`))
  // Load the response as json
  .then(response => response.json())
  // Show the avatar image (githubUser.avatar_url) for 3 seconds (maybe animate it)
  .then(githubUser => {
    let img = document.createElement('img');
    img.src = githubUser.avatar_url;
    img.className = "promise-avatar-example";
    document.body.append(img);

    setTimeout(() => img.remove(), 3000); // (*)
  });

這里的語義比較清楚,每一個(gè) then 調(diào)用都返回一個(gè) Promise,后續(xù)的 then 調(diào)用,必須在前一個(gè) then 調(diào)用返回的 Promise 被 resolve 之后,才能得到執(zhí)行。

不過上述代碼有一個(gè)缺陷:

看 * 所在行的代碼:在頭像完成顯示并被移除后,如果我們想添加一些額外的處理邏輯,應(yīng)該怎么做? 例如,我們想顯示一個(gè)用于編輯該用戶或其他內(nèi)容的表單。

為了使鏈可擴(kuò)展,我們需要返回一個(gè)在頭像完成顯示時(shí)進(jìn)行 resolve 的 Promise.

代碼如下:

fetch('/article/promise-chaining/user.json')
  .then(response => response.json())
  .then(user => fetch(`https://api.github.com/users/${user.name}`))
  .then(response => response.json())
  .then(githubUser => new Promise(function(resolve, reject) { // (*)
    let img = document.createElement('img');
    img.src = githubUser.avatar_url;
    img.className = "promise-avatar-example";
    document.body.append(img);

    setTimeout(() => {
      img.remove();
      resolve(githubUser); // (**)
    }, 3000);
  }))
  // triggers after 3 seconds
  .then(githubUser => alert(`Finished showing ${githubUser.name}`));

也就是說,(*) 行中的 .then 處理程序現(xiàn)在返回新的 Promise,該 Promise 僅在 setTimeout (**) 中的 resolve(githubUser) 調(diào)用后才被解決。 鏈中的下一個(gè) .then 將等待它。

下圖第 5 行新建的 Promise 對(duì)象,這個(gè)對(duì)象在第 13 行會(huì) resolve,這個(gè) resolve 操作,會(huì)觸發(fā)等待它的第 17 行的 then 方法。 

作為一種好的實(shí)踐,異步操作應(yīng)始終返回一個(gè) Promise. 這使得在它之后的計(jì)劃行動(dòng)成為可能;即使我們現(xiàn)在不打算擴(kuò)展鏈,我們以后也可能需要它。

最后我們對(duì)代碼進(jìn)行重構(gòu)。

function loadJson(url) {
  return fetch(url)
    .then(response => response.json());
}

以上的函數(shù)返回一個(gè) Promise,當(dāng) response 的 json 數(shù)據(jù)可用時(shí),這個(gè) promise 后注冊(cè)的 .then 函數(shù)就會(huì)觸發(fā)。

看其消費(fèi)代碼:

26 行 then 里的箭頭函數(shù)觸發(fā)時(shí),user 就是 25 行 user.json 數(shù)據(jù)被反序列化之后形成的 JSON 對(duì)象。

function loadGithubUser(name) {
  return loadJson(`https://api.github.com/users/${name}`);
}

只是對(duì) loadJson 的一層封裝,讓調(diào)用者不需要知道 Github user api 具體的 endpoint.

function showAvatar(githubUser) {
  return new Promise(function(resolve, reject) {
    let img = document.createElement('img');
    img.src = githubUser.avatar_url;
    img.className = "promise-avatar-example";
    document.body.append(img);

    setTimeout(() => {
      img.remove();
      resolve(githubUser);
    }, 3000);
  });
}

返回一個(gè) Promise,在其 executor 里書寫業(yè)務(wù)邏輯,并通過 resolve(githubUser) 將 Promise 狀態(tài)設(shè)置為 fulfilled,方便將來的擴(kuò)展。

最后的完整代碼:

// Use them:
loadJson('/article/promise-chaining/user.json')
  .then(user => loadGithubUser(user.name))
  .then(showAvatar)
  .then(githubUser => alert(`Finished showing ${githubUser.name}`));
  // ...

總結(jié):

如果 .then(或 catch/finally,無關(guān)緊要)處理程序返回一個(gè) Promise,則 Promise 鏈的其余部分會(huì)一直等待,直到這個(gè) pending 的 Promise 被 resolve. 當(dāng) Promise 內(nèi)部的 executor 有數(shù)據(jù)被 resolve 調(diào)用時(shí),resolve 輸入的數(shù)據(jù)(或錯(cuò)誤)會(huì)被進(jìn)一步傳遞到 Promise chain 里的其他 Promise.then 中去。

到此這篇關(guān)于使用 JavaScript Promise 讀取 Github 用戶數(shù)據(jù)的文章就介紹到這了,更多相關(guān) JavaScript Promise 讀取內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論