search

Home  >  Q&A  >  body text

How to execute Promise repeatedly in async function?

<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>
P粉356128676P粉356128676474 days ago441

reply all(2)I'll reply

  • P粉633075725

    P粉6330757252023-08-19 13:31:19

    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

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

    If this is clear to you, please let me know.

    Thanks

    reply
    0
  • P粉770375450

    P粉7703754502023-08-19 13:07:09

    When you create a promise using new Promise(), it starts running immediately. You can test this by running code like new 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.

    const posts = [{ title: 'Post 1' }, { title: 'Post 2' }];
    var count = 3;
    
    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);
        });
    }
    
    const diffFunction = async () => {
        await addPost();
        await addPost();
        showDetails();
    }
    
    diffFunction();

    reply
    0
  • Cancelreply