JavaScript Promise then() ordering

前端 未结 3 1941
天涯浪人
天涯浪人 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:17

    The reason you see 6 early is because you didn't chain, you branched.

    When you call p.then().then().then(), you've got a chain of promises that must execute in the correct order.
    However, if you call p.then().then(); p.then(), you've got 2 promises attached to p - essentially creating a branch, and the 2nd branch will execute along with the first.

    You can fix this by ensuring you chain them together p = p.then().then(); p.then();

    FYI, you almost NEVER want to branch, unless you bring them back together (eg. Promise.all), or are intentionally creating a "fire and forget" branch.

提交回复
热议问题