7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

再帰 with promise pattern

Last updated at Posted at 2013-03-18
  • ふと思いついたのでメモ代わりに
  • promiseの実装としてjQuery.Deferredを使用
function fact(n) {
  var d = $.Deferred();
  setTimeout(function() {
    function onResolved(result) {
      d.resolve(result * n);
    }
    n > 1 ? fact(n - 1).then(onResolved) : d.resolve(n);
  }, 100);
  return d.promise();
}

fact(5).then(console.log.bind(console)); // 120

追記(非同期じゃなくても書けた)

function fact(n) {
  var d = $.Deferred();
  n > 1 ?  fact(n -1).then(function(result) { d.resolve(result * n) }) : d.resolve(n);
  return d.promise();
}

fact(5).then(console.log.bind(console)); // 120

でも普通はこう書く

function fact(n) {
  return $.Deferred().resolve(function fact(n) {
    return n > 1 ? fact(n - 1) * n : n;
  }(n));
}

一般的にPromiseを返す関数にしたければ

function toPromise(fn) {
  return function() {
    var d = $.Deferred();
    try {
      d.resolve(fn.apply(null, arguments));
    } catch (e) {
      d.reject(e);
    }
    return d.promise();
  };
}

toPromise(function fact(n) { return n > 1 ? fact(n - 1) * n : n })(5).then(console.log.bind(console));
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?