Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

let p = sleep(50);

p.then(() => console.log('a')).then(() => console.log('c'));
p.then(() => console.log('b')).then(() => console.log('d'));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

The way that things are queued using setTimeout is exactly that - a queue. If two callbacks are queued with the same 'delay', the callback that was queued first, will fire first.

Edit: I failed to understand the OP's intention initially.

'Branching' promises is what is actually occurring here. Meaning - the 'then-able' being referenced in the first set of then-ables (for a & b) will fire the two provided callbacks at 'the same time' because they both reference the same promise - however - the tricky bit is that they execute in the order that they were queued using the .then(...) of the resolving promise object.

Then the following/subsequent callbacks are queued in their respective orders (c & d).

To answer the question directly: No. The nature of the async actions in a then-able could be anything. However, the functions provided in the OP's then-ables are essentially synchronous, resulting in the intuitive - but entirely misleading - logging order.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...