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

promise

 promise

to4iki

May 20, 2015
Tweet

More Decks by to4iki

Other Decks in Programming

Transcript

  1. Promise ͱݺ͹ΕΔ΋ͷ͕͋ΔΒ͍͠ݴޠ • ECMAScript 6 (Promises A/+) • jQuery.Deferred •

    Java (java.util.concurrent.Future) • Scala (scala.concurrent.Future)
  2. callback pattern getA(function(error, a) { // Aऔಘࣦഊ࣌ͷॲཧ if (error) {

    throw error; } getB(function(error, b) { // Bऔಘࣦഊ࣌ͷॲཧ if (error) { throw error; } getC(function(error, c) { // Cऔಘࣦഊ࣌ͷॲཧ if (error) { throw error; } // a, b, cऔಘ੒ޭ࣌ͷॲཧ done(); }); }); });
  3. ex. getURL function getURL(URL) { return new Promise(function (resolve, reject)

    { var req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function () { if (req.status === 200) { resolve(req.responseText); // ੒ޭ࣌ } else { reject(new Error(req.statusText)); // ࣦഊ࣌ } }; req.onerror = function () { reject(new Error(req.statusText));ɹ// ࣦഊ࣌ }; req.send(); }); } • PromiseίϯετϥΫλ͔ΒPromiseΦϒδΣΫτ(Πϯελϯε)Λ࡞Γฦ͢ • ίϯετϥΫλͷதͰ(ඇಉظ)ॲཧΛߦ͏ • ॲཧͷ੒൱ʹΑͬͯɺresolve<݁Ռͷ஋> ·ͨ͸ reject<ErrorΦϒδΣΫτ> ΛݺͿ
  4. PromiseΦϒδΣΫτ var URL = "http://httpbin.org/get"; getURL(URL).then(function onFulfilled(value){ console.log(value); }).catch(function onRejected(error){

    console.error(error); }); • promiseΦϒδΣΫτʹͦΕͧΕcallbackΛొ࿥ • then Ͱ੒ޭ࣌ʹݺͼग़͢callback(fulfill͞Εͨ) • catchͰࣦഊ࣌ʹݺͼग़͢callback(reject͞Εͨ) • PromiseίϯετϥΫλͷॲཧ݁ՌʹΑͬͯͲͪΒ͔͕ݺ͹ΕΔ
  5. Promise͸஋ͷശ • ࠓ͸·ͩͳ͍͚Ͳকདྷతʹத਎ʢ஋ʣ͕ಘΒΕΔശ • resolve<T> or reject<Error> • ஋͕ೖͬͨ࣌ʹ then

    or catchΛݺͿͱ͍͏ػೳΛ΋ͬͨശ • Optionalͱಉ͡(த਎ʢ஋ʣ͕ۭ͔΋͠Εͳ͍ശ) • Some<T> or None • Eitherͱಉ͡(த਎ʢ஋ʣ͕Τϥʔ͔΋͠Εͳ͍ശ) • Left<Error> or Right<T>
  6. ࿈࠯తʹॻ͚Δ(promise chain) Promise.resolve(2) .then(function(v) { return v * 2; })

    .then(function(v) { return v * v; }) .then(function(v) { console.log(v); }) .catch(function(e) { // Ͳ͔͜Ͱerrror͕ى͖ͨΒ͜͜Ͱcatch͞ΕΔ console.error(e); }) • then΍catch͸ϝιουνΣʔϯͳͷͰ࿈ଓͰॻ͚Δ • then΍catch͸ຖճ৽͍͠promiseΦϒδΣΫτΛฦͯ͠࿈࠯͢Δ
  7. see also • Promise - JavaScript | MDN • https://developer.mozilla.org/ja/docs/Web/JavaScript/

    Reference/Global_Objects/Promise • JavaScript Promiseͷຊ • http://azu.github.io/promises-book • ࠓߋ͚ͩͲPromiseೖ໳ • http://qiita.com/koki_cheese/items/c559da338a3d307c9d88