0

getPosts() loops through an array of posts, builds LIs and places them inside document.body. Works ok.

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

createPost() returns a promise which waits 3 seconds (to simulate client-server delay), adds a post to the array and resolves.

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

The following works as expected. Three LIs are returned, with (undefined):

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

But when getPosts inside .then has a parameter, it is fired without waiting for promise to resolve:

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

Why?

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

2

1 Answer 1

2

In your then you give a callback function.

then(getPosts) will be called with the argument given: getPosts(result)

But getPosts(1)is immediately resolved.

What you want is ()=> getPosts(1)


Edit to clarify the difference between the two syntaxes:

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
2
  • Thanks. Why does getPosts(1) and ()=> getPosts(1) behave differently?
    – marko-36
    Sep 24, 2018 at 12:01
  • I tried to explain it a bit better - see my edit
    – Nigel Nop
    Sep 25, 2018 at 6:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.