Javascript 向.then()中的函数添加参数会破坏JS中的承诺行为

Javascript 向.then()中的函数添加参数会破坏JS中的承诺行为,javascript,promise,Javascript,Promise,getPosts()循环遍历一组帖子,构建LIs并将它们放在document.body中。工作正常 function getPosts(num){ let output =''; posts.forEach((post, index)=>{ output += `<li>${post.title} (${num})</li>`; }); document.body.innerHTML += output; } 以下工作与预期的一样。返回

getPosts()循环遍历一组帖子,构建LIs并将它们放在document.body中。工作正常

function getPosts(num){ 
  let output ='';
  posts.forEach((post, index)=>{
     output += `<li>${post.title} (${num})</li>`;
  });
  document.body.innerHTML += output;
}
以下工作与预期的一样。返回三个LIs,其中包含(未定义):

但是,当getPosts inside.then有一个参数时,它将在不等待promise解决的情况下被激发:

createPost ({title: 'Post Three', body: 'Post Three'})
.then(getPosts(1));
为什么?


中,然后
给出一个回调函数

then(getPosts)
将使用给定的参数调用:
getPosts(result)

但是
getPosts(1)
会立即得到解决

您想要的是
()=>getPosts(1)


编辑以澄清两个语法之间的差异:

const foo = getPosts(1)
//foo is the _Result_ of immediately calling getPosts(1)
//so in your case an array with some objects in it, or undefined
foo(); //CRASH BOOM BURN - foo is not a function

const bar = () => getPosts(1)
//bar is a lambda that can be called to execute getPosts(1)
//At some point in the future or whenever -which is what your then-Block does
const posts = bar(); //Hooray, we have posts

中,然后
给出一个回调函数

then(getPosts)
将使用给定的参数调用:
getPosts(result)

但是
getPosts(1)
会立即得到解决

您想要的是
()=>getPosts(1)


编辑以澄清两个语法之间的差异:

const foo = getPosts(1)
//foo is the _Result_ of immediately calling getPosts(1)
//so in your case an array with some objects in it, or undefined
foo(); //CRASH BOOM BURN - foo is not a function

const bar = () => getPosts(1)
//bar is a lambda that can be called to execute getPosts(1)
//At some point in the future or whenever -which is what your then-Block does
const posts = bar(); //Hooray, we have posts

请使用代码段而不是指向外部服务的链接除了标记为重复项的引用之外,其他引用都是:,请使用代码段而不是指向外部服务的链接除了标记为重复项的引用之外,其他引用都是:,谢谢。为什么getPosts(1)和()=>getPosts(1)的行为有所不同?我试图更好地解释它-请参阅我的编辑谢谢。为什么getPosts(1)和()=>getPosts(1)的行为有所不同?我试图更好地解释它-请参阅我的编辑
const foo = getPosts(1)
//foo is the _Result_ of immediately calling getPosts(1)
//so in your case an array with some objects in it, or undefined
foo(); //CRASH BOOM BURN - foo is not a function

const bar = () => getPosts(1)
//bar is a lambda that can be called to execute getPosts(1)
//At some point in the future or whenever -which is what your then-Block does
const posts = bar(); //Hooray, we have posts