为什么以下代码在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"));
答案 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"));