11
8

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.

Javascript then/catch/finally chainの動作の実験

Last updated at Posted at 2020-04-12

then/catch/finally chainの動作の理解が曖昧なので実験

var p = Promise.resolve(0);

p
.then((v)=>{
  console.log("then1:"+v);
  return Promise.reject(1);
})
.then((v)=>{
  console.log("then2:"+v);
  return Promise.resolve(2);
})
.catch(v=>{
  console.log("catch1:"+v);
  return Promise.reject(-1);
})
.then(v=>{
  console.log("then3:"+v);
  return Promise.resolve(3);
})
.catch(v=>{
  console.log("catch2:"+v);
  //return Promise.resolve(-2);
})
.then(v=>{
  console.log("then4:"+v);
  return Promise.resolve(4);
})
.finally(v=>{
    console.log("finally:"+v);
    return Promise.resolve(100);
})
.then((v)=>{
	console.log("then5:"+v);
})
.catch((v)=>{
	console.log("catch3:"+v);
})

いろいろresolve/rejectをいろいろ変えてjsfiddle で実験してみる.

  1. catchはその前にrejectしたPromiseがある場合にcatchまで飛んでくる. 間にあるthenは飛ばされる.
  2. catchの前にrejectしたPromiseがない場合は、catchはスキップされその後のthenから実行される
  3. catchがresolveを返すとそこで一旦リセットされ、その後のthenが実行される
  4. catchが何も返さない場合も、その後のthenは"undefined"でresolveされた状態で実行される
  5. finallyはどんな時にも実行される. 引数には何も入ってこない.
  6. finallyの後にthen, catchを続けても良い
  7. finallyがその後のthen,catchに与える動作は少し特殊である.
  • finally到達時にresolveである場合
  • rejectするとその後のcatchまで飛びreject値も通知される.
  • resolveをするとその後のthenが実行されるがresolve値を更新することはできない.
  • finally到達時にrejectである場合
  • resolveしてもその後のthenはskipされcatchまで飛ぶ.
  • rejectするとその後のcatchまで飛びreject値も通知される.

つまり、finallyではrejectする場合のみチェーンに影響を与え、resolveは何も影響を与えない。

11
8
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
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?