在.then()中向函数添加参数会破坏JS中promise的行为

时间:2018-09-24 11:17:36

标签: javascript promise

getPosts()循环遍历一系列帖子,构建LI并将其放置在document.body中。可以。

function getPosts(num){ 
  let output ='';
  posts.forEach((post, index)=>{
     output += `<li>${post.title} (${num})</li>`;
  });
  document.body.innerHTML += output;
}

createPost()返回一个等待3秒(模拟客户端-服务器延迟)的promise,在该数组中添加一个帖子,然后解析。

function createPost(post){
     return new Promise((resolve, reject) => {
       setTimeout(()=>{
          posts.push(post);
          const error = false;          
          if (error){
             reject ('Error happened!');
          }else{
             resolve();
          }
       },3000);
    });
 }

以下内容按预期工作。返回三个LI,带有(未定义)

createPost ({title: 'Post Three', body: 'Post Three'})
.then(getPosts);

但是当.post中的getPosts有一个参数时,它将被触发,而无需等待承诺解决:

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

为什么?

https://codepen.io/Marko36/pen/LJoRYN

1 个答案:

答案 0 :(得分:2)

在您的then中,您提供了一个回调函数。

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