Friday, 15 August 2014

JavaScript Promise then() ordering -


I'm still learning javascript promise s, and I came in a behavior that I Does not

  var o = $ (" # output "); Var w = function (s) {o.append (s + ""); } Var p = Promise.resolve (). Then (function () {w (0);}). Then (function () {w (1);}); P.then (function () {w (2); New promise back (function (r) {w (3); r ();}). Then (function () {w (4);})}}) .then (function () {w (5);}); P.then (function () {w (6);});  
  & lt; Script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> & Lt; Div id = "output" & gt; & Lt; / Div & gt;       

I expect these statements to run in sequence - that is, this will be output

  0 1 2 3 4 5 6  

Instead, the output is

  0 1 2 3 6 4 5  
< P> Even remove the promise , what I think, the opposite of the result 1 is before 2 , but there is 5 output before 6 .

Anyone explain this to me?

What I have seen is that reassigning p every time we expect that I will get the order.

You can see that the initial reason for 6 is that you have a series No, you are in the branch

when you call p.then (). Then (). Then () , you have found a series of promises that the right sequence executed in should
However, if you call p.then (). Again (); P.then () , you have 2 promises related to p - essentially make a branch, and the second branch will be executed with the first.

You can make sure that you meet them together p = p.then (). Again (); Pythen ();

FYI, you almost never want to branch, unless you bring them back together (like Promise.all ), or deliberately a "fire And forgetting "Creating Branch"


No comments:

Post a Comment