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

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

javascript - ES6 promise execution order for returned values

Trying to understand the order of execution of ES6 promises, I noticed the order of execution of chained handlers is affected by whether the previous handler returned a value or a promise.

Example

let a = Promise.resolve();
a.then(v => Promise.resolve("A")).then(v => console.log(v));
a.then(v => "B").then(v => console.log(v));
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Going strictly by the ES spec and its queue semantics, the order should be B A, as the additional promise in the first chain would take an additional microtask round. However this does prevent the usual optimisations, such as inspecting the resolution status and fulfillment value synchronously for known promises instead of inefficiently creating callbacks and going through then every time as mandated by the spec.

In any case, you should not write such code, or not rely on its order. You have two independent promise chains - a.then(v => Promise.resolve("A")) and a.then(v => "B"), and when each of those will resolve depends on what their callbacks do, which ideally is something asynchronous with unknown resolution anyway. The Promises/A+ spec does leave this open for implementations to handle synchronous callback functions either way. The golden rule of asynchronous programming in general, and with promises specifically, is to always be explicit about order if (and only if) you care about the order:

let p = Promise.resolve();
Promise.all([
  p.then(v => Promise.resolve("A")),
  p.then(v => "B")
]).then(([a, b]) => {
  console.log(a);
  console.log(b);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...