Khant Min Si Thu
Khant Min Si Thu

Reputation: 328

How to change this promise.then to promise.all with async await?

const posts = [{
        title: 'Post One',
        body: 'This is Post 1'
    },
    {
        title: 'Post Two',
        body: 'This is Post 2'
    },
    {
        title: 'Post Three',
        body: 'This is Post 3'
    }
]

I create the posts array here

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

First I get the post by get Post. Inorder to make it like api request I make with setTimeoutFunction();

function CreatePost(post) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            posts.push(post);
            const error = false;

            if (!error) {
                resolve();
            } else {
                reject('Error Something Went wrong')
            }
        }, 2000)
    })
}

I create the fourth post with CreatePost

function CreateAnotherPost(post) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            posts.push(post);
            const error = false;
            if (!error) {
                resolve(console.log(posts));
            } else {
                reject('something went wrong')
            }
        }, 5000);
    })
}

Here I create another post with the very long wait time

CreateAnotherPost({
    title: 'Post Five',
    body: 'This is post Five'
}).then(CreatePost({
    title: 'Post Four',
    body: 'This is post Four'
})).then(getPosts).catch(error => console.log(error));

I can make it run smoothly with chaining .then. But I don't know how to use promise.all

Upvotes: 1

Views: 424

Answers (3)

jfriend00
jfriend00

Reputation: 707258

You use Promise.all() when you have more than one promise and you want to run those asynchronous operations in parallel. To use it, you just pass Promise.all() an array of promises:

Promise.all([
     CreatePost({title: 'Post Four', body: 'This is post Four'}), 
     CreateAnotherPost({title: 'Post Five', body: 'This is post Five'})
]).then(results => {
    console.log(results);
}).catch(err => {
    console.log(err);
});

The results are then provided in an array that is ordered according to the array of input promises (results come from promises that resolve with a value which yours don't for some unknown reason - that's how you should be communicating the async result). If any of the promises rejects, Promise.all() will reject and you will only get the rejected reason, not any of the other results.

Upvotes: 1

niranjan_harpale
niranjan_harpale

Reputation: 2264

Promise.all takes, an array of promises and executes them in order, synchronously, If one first promise resolves, then it executes the second promise. If any promise rejects then it will go to .catch block of Promise.all.

If all promises resolves successfully, then it will go to the .then block of Promise.all

Promise.all([
    this.CreateAnotherPost({title: 'Post Five',body: 'This is post Five'}),
    this.CreatePost({title: 'Post Four',body: 'This is post Four'})
   ])
   .then((res)=>{
       // todo after all promise resolves successfully
   })
   .catch((err)=>{
       // todo after if any of the promises resolves rejects
   })

Hope this helps!

Upvotes: 1

chans
chans

Reputation: 5260

Promise.all takes a array of promises and waits for all the promises in the array to resolve and returns resolved promoise, if any error occurs in any one of the promise in array, it reached catch block

You can try this approach

Promise.all([CreateAnotherPost({
    title: 'Post Five',
    body: 'This is post Five'
  }),
  CreatePost({
    title: 'Post Four',
    body: 'This is post Four'
  })
]).then(getPosts).catch(error => console.log(error));

Upvotes: 1

Related Questions