LoginSignup
28
28

More than 5 years have passed since last update.

JavaScript Promiseの実行順序(Firefox31とChrome37で違うけどどっちが正しい?)

Posted at

JavaScriptのPromiseで複数のthenを設定した時の動きがFirefox31とChrome37で違った。
コードは以下。

var p = new Promise(function(fulfill, reject){
    console.log("start");
    fulfill("");
});

p.then(function(result){
    console.log("1-1");
}).then(function(result){
    console.log("1-2");
}).then(function(result){
    console.log("1-3");
});

p.then(function(result){
    console.log("2-1")
}).then(function(result){
    console.log("2-2");
}).then(function(result){
    console.log("2-3");
});

Chrome37の結果

以下のような感じ。それぞれが入れ子になりながら動いてる。

start
1-1
2-1
1-2
2-2
1-3
2-3 

Firefox31の結果

以下のような感じ。先のチェーンが全部実行された後に次のチェーンが実行されている。

start
1-1
1-2
1-3
2-1
2-2
2-3

で、どっちが正しいの?

JavaScript Promiseの本 の本を見ると then は常に非同期で実行されるらしく、JavaScriptはキューに貯めてる動きなので、直感的には Chrome の動きのほうが正しく見えるのだが、いったいどっちが正しいんやろう?

28
28
8

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