Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Promiseを実装してみよう

 Promiseを実装してみよう

Hiroki Kumamoto

November 22, 2018
Tweet

More Decks by Hiroki Kumamoto

Other Decks in Programming

Transcript

  1. ྫ: BKBY \ VSMVSM  TVDDFTT \BMFSU lTVDDFTTz ^ 

    FSSPS \BMFSU lFSSPSz ^ ^  WBSQSPNJTFBKBY \VSMVSM^  QSPNJTFUIFO \BMFSU lTVDDFTTz ^  DBUDI \BMFSU lFSSPSz ^ 
  2. • Promise.prototype.then(), Promise.prototype.catch()΋PromiseΛฦ͢ͷ ͰɺνΣʔϯʢ࿈࠯ʣͰ͖Δ PromiseͷϝϦοτ BKBY \VSMVSM^  UIFO EBUB

    BKBY \VSMVSM ʜ^  UIFO EBUB BKBY \VSMVSM ʜ^  DBUDI \BMFSU lFSSPSz ^ 
  3. PromiseΛ࣮૷ͯ͠ΈΑ͏ • લ৬Ͱ૊ΈࠐΈϒϥ΢β޲͚(es3)ʹ࣮૷ • es3ͳه๏Ͱ࣮૷ • catch͕༧໿ޠͳͷΛճආͳͲ • kumabook/yakusoku (174ߦ:

    4KB) • jQuery.Deferred(Promiseͷલ਎)͕ಋೖ͞Εͨͷ͕ jQuery 1.5 (2011/1/31) • ࠓ΍ඪ४APIʹͳͬͯ࢖͑ͯ౰ͨΓલ • ͳΜͱͳ͘࢖͑ͯཧղͨ͠ؾʹͳ͍͕ͬͯͨࣗ෼Ͱ࣮૷ͯ͠ษڧʹͳͬͨ
  4. PromiseΦϒδΣΫτͷੜ੒ • executor • resolveͱrejectΛҾ਺ʹͱΔ • resolve͔rejectͷͲͪΒ͔ҰํΛݺͼग़͢ • ੒ޭͨ͠Βresolveɻࣦഊͨ͠Βreject •

    ͙͢ʹ࣮ߦ͞ΕΔ WBSQSPNJTFOFX1SPNJTF SFTPMWF SFKFDU \ TFU5JNFPVU \SFTPMWF GPP ^   ^ 
  5. Promiseͷঢ়ଶભҠ QFOEJOH GVMpMMFE SFKFDUFE 3VO FYFDVUPS SFTPMWF SFKFDU PS
 UISPXFSSPS

    $BMM TVDDFTT IBOEMFS $BMM FSSPS IBOEMFS QSPNJTFͷঢ়ଶ QSPNJTFͷಈ࡞ FYFDVUPSͷಈ࡞
  6. PromiseΛ࣮૷ͯ͠ΈΑ͏ • PromiseͷϓϩύςΟ • status: ঢ়ଶ(pending, fulfilled, rejected) • value:

    ੒ޭͨ࣌͠ͷ݁Ռɻ΋͘͠͸ࣦഊͨ͠ཧ ༝ • handlers: ੒ޭͨ࣌͠ɺࣦഊͨ࣌͠ͷؔ਺ͷϖΞ ΛΩϡʔ(഑ྻ)Ͱอ࣋
  7. Ҿ਺Ͱ౉͖ͬͯͨexecutorΛ࣮ߦ 1SPNJTFQSPUPUZQFSVOGVODUJPO FYFDVUPS \ WBSTFMGUIJT USZ\ FYFDVUPS GVODUJPO WBMVF \

    TFMGGVMpMM WBMVF  ^ GVODUJPO F \ TFMGSFKFDU F  ^  ^DBUDI F \ TFMGSFKFDU F  ^ ^ FYDFDVUPSࣗମ͕Τϥʔʹͳͬ ͨΒΩϟονͯ͠ΤϥʔΦϒδΣΫτͱ ͱ΋ʹϋϯυϥʔ΁ FYDFDVUPS͕SFTPMWFͱ SFKFDUΛݺΜͰ͘ΕΔͷͰͦͷ݁Ռ Λϋϯυϥʔ΁
  8. Promiseͷ࣮ߦঢ়ଶ QFOEJOH GVMpMMFE SFKFDUFE 3VO FYFDVUPS SFTPMWF SFKFDU PS
 UISPXFSSPS

    $BMM TVDDFTT IBOEMFST $BMM FSSPS IBOEMFST TFMGGVMpMM TFMGSFKFDU
  9. BKBY \VSMHFU6TFS6SM^  UIFO EBUB \ JG EBUBJT"ENJO \ SFUVSOBKBY

    \VSMHFU%BUB6SM^  ^ SFUVSO<> ^ UIFO EBUB VQEBUF7JFX EBUB  DBUDI \BMFSU lFSSPSz ^  QSPNJTFͱඇQSPNJTFͳ஋ Λಁաతʹѻ͑Δ
  10. 1SPNJTFQSPUPUZQFUIFOGVODUJPO PO'VMpMMFE PO3FKFDUFE \ WBSTFMGUIJT SFUVSOOFX1SPNJTF GVODUJPO SFTPMWF SFKFDU \

    TFMGFORVFVF0S&YFDVUF)BOEMFS GVODUJPO WBMVF \ JG WBMVFJOTUBODFPG1SPNJTF \ SFUVSOSFTPMWF WBMVFUIFO PO'VMpMMFE PO3FKFDUFE  ^FMTF\ SFUVSOSFTPMWF PO'VMpMMFE WBMVF  ^ ^ GVODUJPO F \ ʜ ^  ^  ^ ී௨ͷ஋ͷ৔߹ UIFOBCMFͷ஋ͷ৔߹
  11. Promise API • ࠓճ͸঺հͨ͠API • new Promise() • Promise.prototype.then() •

    ࢒Γ • Promise.prototype.catch() • Promise.resolve(), Promise.reject() • Promise.all(), Promise.race()
  12. ·ͱΊ • PromiseΛ࣮૷Λ঺հ • new Promise()ͱPromise.prototype.then() • ࣮૷͸γϯϓϧͱࢥ͍͖΍ͦͦ͜͜ෳࡶ • Stateful

    + asyncͳͷͰɺςετɾσόοάͣ͠Β͍ • Կؾͳ͘࢖͍ͬͯΔAPIͷΛ༗Γ೉ΈΛײ͡ΒΕ·͢
  13. ࢀߟࢿྉ • Promise - JavaScript | MDN • PromiseΛ࢖͏ -

    JavaScript | MDN • Promises/A+ • kumabook/yakusoku