Adding a parameter to a function in .then() breaks the behaviour of a promise in JS

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Adding a parameter to a function in .then() breaks the behaviour of a promise in JS



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




1 Answer
1



In your then you give a callback function.


then



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


then(getPosts)


getPosts(result)



But getPosts(1)is immediately resolved.


getPosts(1)



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


()=> getPosts(1)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS