【问题标题】:Adding a parameter to a function in .then() breaks the behaviour of a promise in JS [duplicate]在 .then() 中向函数添加参数会破坏 JS 中承诺的行为 [重复]
【发布时间】:2019-02-27 21:30:49
【问题描述】:

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 秒(模拟客户端-服务器延迟)的承诺,向数组添加一个帖子并解析。

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

以下按预期工作。返回三个 LI,分别为 (undefined):

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

【问题讨论】:

标签: javascript promise


【解决方案1】:

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

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

但是getPosts(1)会立即解决。

你想要的是()=&gt; 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) 行为不同?
  • 我试图更好地解释它 - 请参阅我的编辑
猜你喜欢
  • 2016-12-06
  • 2020-06-18
  • 2018-11-29
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 2016-01-21
相关资源
最近更新 更多