Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 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 Reply

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...