将promise与promise链接会导致意外的执行顺序

时间:2019-10-08 15:27:16

标签: javascript promise

为什么以下代码在baz, done之前打印1, 2, 3

const bar = () => Promise.resolve([1, 2, 3]);
const cat = e => {
  console.log(e);
  return Promise.resolve(e);
};
const foo = () =>
  bar()
    .then(arr => Promise.all(arr.map(e => cat(e))))
    .then(console.log("baz"));

foo().then(console.log("done"));

2 个答案:

答案 0 :(得分:5)

您正在立即执行console.log(),而不是将其传递给.then()中的回调函数。可以做到:

const bar = () => Promise.resolve([1, 2, 3]);

const cat = e => {
  console.log(e);
  return Promise.resolve(e);
};

const foo = () =>
  bar()
    .then(arr => Promise.all(arr.map(e => cat(e))))
    .then(() => console.log("baz"));
    
foo().then(() => console.log("done"));

答案 1 :(得分:0)

您可能忘记了将console.log嵌入到箭头函数中,因此适当推迟了它们的执行:

const bar = () => Promise.resolve([1, 2, 3]);
const cat = e => {
  console.log(e);
  return Promise.resolve(e);
};
const foo = () =>
  bar()
    .then(arr => Promise.all(arr.map(e => cat(e))))
    .then(() => console.log("baz"));

foo().then(() => console.log("done"));