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

Promise完全攻略

kaidouji85
October 14, 2016

 Promise完全攻略

kaidouji85

October 14, 2016
Tweet

More Decks by kaidouji85

Other Decks in Technology

Transcript

  1. ίʔϧόοΫͰॻ͍ͨ৔߹ processA(function() { processB(function() { processC(function() { processD(); }); });

    }); ؔ਺ΛݺͿͨͼʹωετ͕ਂ͘ͳΔ ͜ΕͰ෼ذ΍ྫ֎ॲཧ͕ೖΔͱࢮʹͦ͏ ͜͏͍͏ͷΛίʔϧόοΫ஍ࠈͱ͍͏
  2. PromiseͰॻ͍ͨ৔߹ processA() .then(function() { return processB(); }).then(function() { return processC();

    }).then(function() { return processD(); }); ωετ͸1ஈ֊ਂ͘ͳΔ͕ɺͦΕҎ্͸ਂ͘ͳΒͳ͍ ίʔϧόοΫ஍ࠈΛ͋Δఔ౓ࠀ෰Ͱ͖͍ͯΔ
  3. ൺֱͯ͠Έ·͠ΐ͏ processA(function() { processB(function() { processC(function() { processD(); }); });

    }); processA() .then(function() { return processB(); }).then(function() { return processC(); }).then(function() { return processD(); }); Promiseͷํ͕෼͔Γ΍͍͢
  4. ɹྫ֎ॲཧ΋εϚʔτʹॻ͚Δ processA() .then(() => processB()) .then(() => processC()) .then(() =>

    processD()) .catch(() => { //ྫ֎ॲཧ }) Ͳͷؔ਺Ͱྫ֎͕ग़ͯ΋ɺcatchʹඈΜͰऴྃ͢Δ try-catchΈ͍ͨͳ࢖͍ํ͕Ͱ͖Δ
  5. طଘؔ਺ΛPromiseԽ // ݩͷؔ਺ function processA(cb) { // ͕͔͔࣌ؒΔॲཧ cb(); }

    // PromiseԽ function processAWithPromise() { return Promise((resolve, reject) => { processA(resolve); })); }
  6. طଘؔ਺ΛPromiseԽ // PromiseԽ function processAWithPromise() { return Promise((resolve, reject =>

    { processA(resolve); })); } શମΛPromiseͰׅΔ ݩͷؔ਺ͷίʔϧόοΫʹresolveΛ౉͢