This question already has an answer here:
javascript promise chains not waiting for previous promise to execute
                                
                                    (1个答案)
                                
                        
                2年前关闭。
            
        

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);


但是,当.then中的getPosts具有参数时,它将被触发,而无需等待promise解决:

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


为什么?

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

最佳答案

在您的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

关于javascript - 在.then()中向函数添加参数会破坏JS中promise的行为。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52478165/

10-13 00:24