JavaScript Promise then() ordering

前端 未结 3 1954
天涯浪人
天涯浪人 2020-12-09 05:08

I\'m still learning JavaScript Promises, and I came across a behavior I don\'t understand.

3条回答
  •  我在风中等你
    2020-12-09 05:23

    What does r() do?

    The ordering is indeterminate because you're thenning on the same promise -> this specifically refers to the second and third chain.

    If you were doing the following, then order can be guaranteed:

    var p = Promise.resolve().then(function() {
        w(0);
    }).then(function() {
        w(1);
    });
    
    // Key difference, continuing the promise chain "correctly".
    p = p.then(function() {
        w(2);
        return new Promise(function(r) {
            w(3);
            r();
        }).then(function() {
            w(4);
        });
    }).then(function() {
      w(5);
    });
    
    p.then(function() {
      w(6);
    });
    

提交回复
热议问题