×ðÁú¿­Ê±

jsÖÐpromiseµÄÓ÷¨

promise ÊÇ javascript ÖÐÓÃÓÚÒì²½²Ù×÷µÄ¹¤¾ß¡£ËüÌṩÁËÒ»ÖÖͳһµÄ·½·¨À´´¦Öóͷ£Òì²½²Ù×÷£¬¼ò»¯ÁË´úÂ룬²¢Ìṩ¹ýʧ´¦Öóͷ£»úÖÆ¡£Ê¹Óà promise Éæ¼°½¨Éè promise¡¢´¦Öóͷ£Ëü£¨Ê¹Óà then() ºÍ catch() ÒªÁ죩¡¢Á´½ÓºÍ×éºÏËüÃÇ£¬ÒÔ´¦Öóͷ£Òì²½²Ù×÷¡£

Promise ÔÚ JavaScript ÖеÄÓ÷¨

ʲôÊÇ Promise£¿

Promise ÊÇ JavaScript ÖÐÓÃÓÚÒì²½²Ù×÷µÄÒ»ÖÖ¹¤¾ß¡£ËüÌåÏÖÒ»¸öδÀ´¿ÉÄܽâ¾ö£¨Í¨¹ýŲÓà resolve()£©»ò¾Ü¾ø£¨Í¨¹ýŲÓà reject()£©µÄÒì²½²Ù×÷µÄЧ¹û¡£

ΪºÎʹÓà Promise£¿

Promise ÌṩÁË´¦Öóͷ£Òì²½²Ù×÷µÄͳһ·½·¨£¬Ê¹´úÂë¸üÒ×ÓÚ±àдºÍÃ÷È·£º

×èÖ¹Á˻ص÷º¯ÊýµÄǶÌ×£¬Ê¹´úÂë¸ü¾ß¿É¶ÁÐÔ¡£

ÔÊÐíÇáËɵØÁ´½ÓºÍ×éºÏ¶à¸öÒì²½²Ù×÷¡£

Ìṩ¹ýʧ´¦Öóͷ£»úÖÆ£¬È·±£Òì²½²Ù×÷Òì³£²»»áÒâÍâÖÕÖ¹Ó¦ÓóÌÐò¡£

ÔõÑùʹÓà Promise£¿

½¨ÉèÒ»¸ö Promise£º

const promise = new Promise((resolve, reject) => {...});

µÇ¼ºó¸´ÖÆ

ʹÓà then() ÒªÁì´¦Öóͷ£ Promise£º

promise.then(
  (result) => {
    // µ± Promise ½â¾öʱŲÓÃ
  },
  (error) => {
    // µ± Promise ¾Ü¾øʱŲÓÃ
  }
);

µÇ¼ºó¸´ÖÆ

ʹÓà catch() ÒªÁì½ö´¦Öóͷ£¾Ü¾ø£º

promise.catch((error) => {
  // µ± Promise ¾Ü¾øʱŲÓÃ
});

µÇ¼ºó¸´ÖÆ

Á´½ÓºÍ×éºÏ Promise£º

Promise ¿ÉÒÔͨ¹ý then() µÄ·µ»ØÖµ¾ÙÐÐÁ´½Ó£º

promise1.then((result1) => {
  return promise2.then((result2) => {
    return { result1, result2 };
  });
}).then((combinedResult) => {
  // Á½¸ö Promise ¶¼Òѽâ¾ö
});

µÇ¼ºó¸´ÖÆ

´¦Öóͷ£Òì²½²Ù×÷µÄʾÀý£º

»ñÈ¡Óû§Êý¾Ý£º

const getUserData = () => {
  return new Promise((resolve, reject) => {
    // Ä£ÄâÒì³ÌÐòÓÃ
    setTimeout(() => {
      if (Math.random() > 0.5) {
        resolve({ name: "John Doe" });
      } else {
        reject(new Error("Could not fetch user data"));
      }
    }, 1000);
  });
};

µÇ¼ºó¸´ÖÆ

ʹÓà Promise »ñÈ¡Êý¾Ý²¢½«ÆäÏÔʾµ½¿ØÖÆ̨£º

getUserData()
  .then((userData) => {
    console.log(`User name: ${userData.name}`);
  })
  .catch((error) => {
    console.log(`Error: ${error.message}`);
  });

µÇ¼ºó¸´ÖÆ

ÒÔÉϾÍÊÇjsÖÐpromiseµÄÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±ÊµÊ±ÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
¡¾ÍøÕ¾µØͼ¡¿¡¾sitemap¡¿