use*_*814 4 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"));Run Code Online (Sandbox Code Playgroud)
您正在立即执行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"));Run Code Online (Sandbox Code Playgroud)