How to execute Promise repeatedly in async function?
P粉356128676
2023-08-18 14:54:42
<p>I'm learning promise and async await, here I want to call the addPost function and push an object twice, then I want to loop through the object array to see the result, but in this code the result is not as expected. Here, when the code executes to the showDetails() function, it only shows 3 objects when there should be four objects, what am I missing here? </p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">const posts = [{ title: 'Post 1' }, { title: 'Post 2' }];
var count = 3;
const diffFunction = async () => {
const addPost = new Promise((resolve, reject) => {
setTimeout(() => {
posts.push({ title: `Post ${count}` });
count ;
resolve(count);
}, 1000)
})
const deletePost = new Promise((res, rej) => {
setTimeout(() => {
const deltedPost = posts.pop();
res(deltedPost);
}, 2000)
})
const showDetails = () => {
posts.forEach(element => {
console.log(element.title);
});
}
await addPost;
await addPost;
showDetails();
}
diffFunction();</pre>
<p><br /></p>
Here, your addPost is not a promise function. That's why when you write "await addPost" it looks like it reinitializes the variable addPost. In order for this to work, you need to call the promise function. This way it will perform the promise work after you call it.
The following is your modified code
If this is clear to you, please let me know.
Thanks
When you create a promise using
new Promise()
, it starts running immediately. You can test this by running code likenew Promise(() => { console.log("hello") })
in the console - you should see a log immediately.You can achieve the behavior you want by defining a function that returns a new Promise. This way, your promise will only run when the function is called, and each function call will return a different Promise.