LoginSignup
1
1

More than 5 years have passed since last update.

後続関数のpipeについて

Posted at

後続関数pipe()の処理についてのメモ
pipe()の機能は2つあり

  • 引数を変更して渡すことができる
  • Defferredオブジェクトの遷移状態の起点をpipe()で示した位置にし、チェーンさせることができる。例は以下の通り。
js
//非同期処理
 const foo = () => {
  var d = new Deferred();
  setTimeout(() => {
    alert('foo');
    d.resolved();
  }, 500);
 };

//非同期処理
const bar = () => {
  var d = new Deferred();
  setTimeout(() => {
    alert('foo');
    d.resolved();
  }, 1000);
};

//同期処理
const baz = () => {
    alert('foo');
};

foo().done(bar).done(baz);  //発生順は、foo baz bar
foo().pipe(bar).done(baz);  //発生順は、foo bar baz



チェーンで書かれているので、期待する発生順は、foo => bar => baz

しかし、1つめではfoo => baz => barになる
done()で設定する後続関数は、fooで作成されたDefferredオブジェクトの状態に依存するため、fooが発生したとき、barとbazの処理が可能になる。そのため、同期処理であるbazの方が早く処理が終わるため、発生順は、foo baz bar。

2爪の処理では、pipe(bar)としている。その結果、barで作成されたDefferredオブジェクトに状態が依存するようになるため、barの発生をまち、bazが発生する。

1
1
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
1
1