最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript中Promise講解和使用方法代碼

 更新時(shí)間:2026年01月26日 10:18:34   作者:新節(jié)  
這篇文章主要介紹了JavaScript中Promise講解和使用方法的相關(guān)資料,Promise是處理異步操作的優(yōu)秀方案,可以使代碼更加簡(jiǎn)潔、易讀、易維護(hù),避免回調(diào)地獄和嵌套過(guò)深的問(wèn)題,需要的朋友可以參考下

PromiseJavaScript 異步編程的核心解決方案,它解決了傳統(tǒng)回調(diào)地獄問(wèn)題,提供了更優(yōu)雅的異步控制流。

面試官:談?wù)勀銓?duì) Promise 的理解?

回答:

Promise 用來(lái)解決異步回調(diào)問(wèn)題,由于 js
是單線程的,很多異步操作都是依靠回調(diào)方法實(shí)現(xiàn)的,這種做法在邏輯比較復(fù)雜的回調(diào)嵌套中會(huì)相當(dāng)復(fù)雜;也叫做回調(diào)地獄;

promise 用來(lái)將這種繁雜的做法簡(jiǎn)化,讓程序更具備可讀性,可維護(hù)性;promise
內(nèi)部有三種狀態(tài),pending,fulfilled,rejected;

pending 表示程序正在執(zhí)行但未得到結(jié)果,即異步操作沒(méi)有執(zhí)行完畢,

fulfilled 表示程序執(zhí)行完畢,且執(zhí)行成功,

rejected 表示執(zhí)行完畢但失敗;這里的成功和失敗都是邏輯意義上的;并非是要報(bào)錯(cuò)。

其實(shí),promise 和回調(diào)函數(shù)一樣,都是要解決數(shù)據(jù)的傳遞和消息發(fā)送問(wèn)題,promise 中的 then
一般對(duì)應(yīng)成功后的數(shù)據(jù)處理,catch 一般對(duì)應(yīng)失敗后的數(shù)據(jù)處理。

一、Promise 基礎(chǔ)概念

1.1 什么是 Promise?

Promise 是一個(gè)表示異步操作最終完成或失敗的對(duì)象,它有三種狀態(tài):

  • pending(進(jìn)行中)
  • fulfilled(已成功)
  • rejected(已失敗)

1.2 創(chuàng)建 Promise

const promise = new Promise((resolve, reject) => {
  // 異步操作
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve("操作成功");
    } else {
      reject("操作失敗");
    }
  }, 1000);
});

1.3 使用 Promise

promise
  .then((result) => {
    console.log(result); // "操作成功"
  })
  .catch((error) => {
    console.error(error); // "操作失敗"
  });

二、Promise 自帶方法

2.1 靜態(tài)方法

Promise.resolve()

創(chuàng)建一個(gè)立即解析的 Promise:

Promise.resolve("立即返回").then(console.log); // "立即返回"

Promise.reject()

創(chuàng)建一個(gè)立即拒絕的 Promise:

Promise.reject("錯(cuò)誤").catch(console.error); // "錯(cuò)誤"

Promise.all()

Promise.all()方法用于將多個(gè) Promise 實(shí)例,包裝成一個(gè)新的 Promise 實(shí)例。等待所有 Promise 完成,或任意一個(gè)失敗。

“致命傷”:一個(gè)失敗,全盤皆輸

// 假設(shè)有三個(gè)異步請(qǐng)求:獲取用戶信息、獲取商品列表、獲取消息通知
const fetchUserInfo = fetch("/api/user");
const fetchProducts = fetch("/api/products");
const fetchNotifications = fetch("/api/notifications");

Promise.all([fetchUserInfo, fetchProducts, fetchNotifications])
  .then(([userInfo, products, notifications]) => {
    // 只有當(dāng)三個(gè)請(qǐng)求都成功時(shí),才會(huì)進(jìn)入這里
    renderUserPage(userInfo, products, notifications);
  })
  .catch((error) => {
    // 如果任何一個(gè)請(qǐng)求失敗,就會(huì)跳到這里
    console.error("有一個(gè)請(qǐng)求失敗了:", error);
    showErrorPage("頁(yè)面加載失敗,請(qǐng)重試!");
  });

Promise.race()

返回最先完成的 Promise(無(wú)論成功或失敗):

const p1 = new Promise((res) => setTimeout(res, 100, "慢"));
const p2 = new Promise((res) => setTimeout(res, 50, "快"));

Promise.race([p1, p2]).then((winner) => {
  console.log(winner); // "快"
});

Promise.allSettled()

為了解決 Promise.all 一個(gè)失敗,全盤皆輸?shù)倪@個(gè)痛點(diǎn),ES2020 引入了 Promise.allSettled 方法。它的行為更加寬容和穩(wěn)?。?/p>

  • 等待所有:它會(huì)等待所有輸入的 Promise 都“敲定”(settled),即無(wú)論是成功(fulfilled)還是失?。╮ejected)。
  • 永不失敗:Promise.allSettled 自身永遠(yuǎn)不會(huì)被 reject,它總是會(huì)成功返回一個(gè)數(shù)組。
  • 詳情可知:返回的數(shù)組中的每個(gè)對(duì)象都包含了每個(gè) Promise 的最終狀態(tài)和結(jié)果(或原因)。

每個(gè)結(jié)果對(duì)象都有兩種形態(tài):

  • 成功:{ status: 'fulfilled', value: 結(jié)果值 }
  • 失?。?code>{ status: 'rejected', reason: 錯(cuò)誤原因 }

如何使用 Promise.allSettled:

Promise.allSettled([fetchUserInfo, fetchProducts, fetchNotifications]).then((results) => {
  // 注意:這里永遠(yuǎn)不會(huì) catch
  // results 是一個(gè)包含三個(gè)對(duì)象的數(shù)組
  const userInfo = results[0].status === "fulfilled" ? results[0].value : null;
  const products = results[1].status === "fulfilled" ? results[1].value : null;
  const notifications = results[2].status === "fulfilled" ? results[2].value : null; // 我們可以針對(duì)每個(gè)結(jié)果進(jìn)行精細(xì)化處理

  if (userInfo && products) {
    // 只要核心數(shù)據(jù)(用戶和商品)還在,就渲染頁(yè)面
    renderUserPage(userInfo, products, notifications); // notifications 可能是 null
    if (!notifications) {
      showToast("通知獲取失敗,不影響主要功能");
    }
  } else {
    // 如果核心數(shù)據(jù)缺失,再顯示錯(cuò)誤頁(yè)
    showErrorPage("核心數(shù)據(jù)加載失敗");
  }
});
// 不需要 .catch,因?yàn)樗肋h(yuǎn)不會(huì)被觸發(fā)

使用 Promise.allSettled 優(yōu)勢(shì):

  • 體驗(yàn)提升:即使通知接口掛了,用戶依然能看到頁(yè)面主體內(nèi)容,只會(huì)收到一個(gè)輕量的提示。
  • 韌性增強(qiáng):?jiǎn)蝹€(gè)接口的失敗不會(huì)導(dǎo)致整個(gè)頁(yè)面或功能的崩潰。
  • 信息完整:我們可以確切地知道每個(gè)任務(wù)的執(zhí)行結(jié)果,并據(jù)此做出更細(xì)致的 UI 響應(yīng)。

Promise.any()

返回第一個(gè)成功的 Promise(忽略失?。?/p>

const p1 = Promise.reject("錯(cuò)誤1");
const p2 = Promise.resolve("成功");

Promise.any([p1, p2]).then((firstSuccess) => {
  console.log(firstSuccess); // "成功"
});

2.2 實(shí)例方法

.then()

處理 Promise 的成功狀態(tài):

fetch("/api")
  .then((response) => response.json())
  .then((data) => console.log(data));

.catch()

捕獲 Promise 鏈中的錯(cuò)誤:

fetch("/api")
  .then((response) => response.json())
  .catch((error) => console.error("請(qǐng)求失敗:", error));

.finally()

無(wú)論成功或失敗都會(huì)執(zhí)行:

fetch("/api")
  .then((response) => response.json())
  .finally(() => console.log("請(qǐng)求結(jié)束"));

三、Promise 高級(jí)技巧

3.1 鏈?zhǔn)秸{(diào)用

function getUser(id) {
  return fetch(`/users/${id}`)
    .then((response) => response.json())
    .then((user) => fetch(`/profile/${user.profileId}`))
    .then((response) => response.json());
}

3.2 錯(cuò)誤處理策略

// 方式1:每個(gè) then 后單獨(dú) catch
fetch("/api")
  .then((res) => res.json())
  .catch(handleJSONError)
  .then((data) => process(data))
  .catch(handleProcessError);

// 方式2:全局 catch
fetch("/api")
  .then((res) => res.json())
  .then((data) => process(data))
  .catch(handleAnyError);

3.3 取消 Promise

原生 Promise 無(wú)法取消,但可以通過(guò)封裝實(shí)現(xiàn):

function cancellablePromise(promise) {
  let isCancelled = false;

  const wrappedPromise = new Promise((resolve, reject) => {
    promise.then((value) => !isCancelled && resolve(value)).catch((error) => !isCancelled && reject(error));
  });

  return {
    promise: wrappedPromise,
    cancel: () => {
      isCancelled = true;
    }
  };
}

3.4 Promise 化回調(diào)函數(shù)

將回調(diào)風(fēng)格的函數(shù)轉(zhuǎn)換為 Promise:

const fs = require("fs");

function readFilePromise(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
}

四、Promise 與 async/await

4.1 基本轉(zhuǎn)換

// Promise 風(fēng)格
function getData() {
  return fetch("/api").then((res) => res.json());
}

// async/await 風(fēng)格
async function getData() {
  const res = await fetch("/api");
  return res.json();
}

4.2 錯(cuò)誤處理對(duì)比

// Promise
fetch("/api")
  .then((res) => res.json())
  .catch(console.error);

// async/await
try {
  const res = await fetch("/api");
  const data = await res.json();
} catch (err) {
  console.error(err);
}

五、常見(jiàn)問(wèn)題與解決方案

5.1 Promise 內(nèi)存泄漏

未處理的 Promise 拒絕會(huì)導(dǎo)致內(nèi)存泄漏:

// 錯(cuò)誤示范(未捕獲的拒絕)
function riskyOperation() {
  return new Promise((_, reject) => {
    setTimeout(reject, 1000, "錯(cuò)誤");
  });
}

// 正確做法
riskyOperation().catch(() => {});

5.2 并行與順序執(zhí)行

// 順序執(zhí)行
async function sequential() {
  await task1();
  await task2(); // 等待 task1 完成
}

// 并行執(zhí)行
async function parallel() {
  await Promise.all([task1(), task2()]);
}

六、總結(jié)

Promise 的核心優(yōu)勢(shì):

  1. 鏈?zhǔn)秸{(diào)用:解決回調(diào)地獄
  2. 統(tǒng)一錯(cuò)誤處理:通過(guò) .catch() 集中管理
  3. 組合能力強(qiáng)Promise.all/race 等實(shí)現(xiàn)復(fù)雜控制流

最佳實(shí)踐建議:

  • 始終返回 Promise 鏈(避免中斷)
  • 使用 async/await 提升可讀性
  • 不要忘記錯(cuò)誤處理
// 終極實(shí)踐示例
async function getFullData() {
  try {
    const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
    return { user, posts };
  } catch (error) {
    console.error("加載失敗:", error);
    throw error; // 向上傳遞
  }
}

常用方法的區(qū)別

方法核心邏輯成功條件失敗條件典型使用場(chǎng)景
Promise.all(iterable)“全部成功”
等待所有 Promise 完成
所有 Promise 都成功 (fulfilled)任意一個(gè) Promise 失敗 (rejected)并行處理多個(gè)相互依賴的任務(wù),如:同時(shí)上傳多張圖片、同時(shí)獲取多個(gè) API 數(shù)據(jù)以渲染頁(yè)面。
Promise.race(iterable)“競(jìng)賽”
取最先完成(無(wú)論成?。┑?Promise 結(jié)果
最先完成的 Promise 是成功 (fulfilled)最先完成的 Promise 是失敗 (rejected)1. 設(shè)置超時(shí)/競(jìng)速:為異步操作添加超時(shí)限制。
2. 從多個(gè)最快響應(yīng)的來(lái)源(如 CDN)獲取資源。
Promise.allSettled(iterable)“無(wú)論成敗”
等待所有 Promise 最終敲定 (settled)
總是成功
(返回每個(gè) Promise 的最終狀態(tài)和結(jié)果數(shù)組)
不會(huì)失敗當(dāng)需要知道每個(gè)異步操作的最終結(jié)果時(shí),如:批量提交表單,無(wú)論單個(gè)成功或失敗都需要記錄日志或進(jìn)行下一步處理。
Promise.any(iterable)“任一成功”
取最先成功的 Promise 結(jié)果
任意一個(gè) Promise 成功 (fulfilled)所有 Promise 都失敗 (rejected)1. 尋找最快可用資源:從多個(gè)鏡像服務(wù)器下載同一個(gè)文件,使用最先響應(yīng)的。
2. 提供備用方案,只要一個(gè)成功即可。

快速選擇指南

當(dāng)你面對(duì)多個(gè)異步操作時(shí),可以這樣選擇:

  • 需要所有操作都成功才能繼續(xù) → Promise.all()
  • 只需第一個(gè)完成的操作結(jié)果(無(wú)論成?。?→ Promise.race()
  • 需要知道每個(gè)操作的最終結(jié)果(無(wú)論成敗) → Promise.allSettled()
  • 只需第一個(gè)成功的操作結(jié)果Promise.any()

總結(jié)

到此這篇關(guān)于JavaScript中Promise講解和使用方法的文章就介紹到這了,更多相關(guān)js Promise使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

龙陵县| 岳西县| 石泉县| 涞水县| 长葛市| 平顶山市| 河间市| 化德县| 新巴尔虎左旗| 卓尼县| 维西| 三河市| 贵德县| 佛教| 循化| 泰和县| 冷水江市| 江西省| 大宁县| 林周县| 涡阳县| 佛山市| 洛浦县| 浠水县| 肃宁县| 禹州市| 榆中县| 天台县| 新平| 老河口市| 绥中县| 儋州市| 台北县| 浦城县| 乐业县| 灵台县| 镶黄旗| 秭归县| 罗甸县| 班玛县| 中阳县|