简体   繁体   中英

Make Multiple Post Requests In Axios

What I have been trying to do is hit an endpoint for my blog posts and then with this data remove extra layout markup that came in from Wordpress. I am using Axios to make the request and then transform response option in order to modify the data to remove the extra markup from the "post_body" object inside my response. This works on a single blog post but when I try to do this all my blog blog posts it return an object of 20 or so blog posts. What I want to do is loop through the objects transform my data and then make a post request back to another API to publish my blog post. What I can't figure out if this will be possible once my promise is resolved. Would I be able to create another for loop within the .then and find my "post_body" object and make the post request. Not sure if I am thinking about this in the right way or not. Any help is much appreciated.

var fieldName = "et_pb";
var regExp = new RegExp("\\[\/?(" + fieldName + ".*?)\\]", "g");

function getBlogPosts() {
  return axios.get(allPosts, {
    transformResponse: axios.defaults.transformResponse.concat(function(data, headers) {
        // use data I passed into the function and the objects from the API
        // pass in data into the function using forEach this will return an array
        data.objects.forEach(function(i) {
            // use the returned array on Objects.key to find the name of the array
            Object.keys(i).forEach(function(k) {
                // if the key equals execute code
                // console.log(k);
                if (k === "post_body") {
                    // fire Regex
                    data[k] = i[k].replace(regExp, '');
                    // console.log(data[k])

                }
            })
        })
        return data;
    })
})
}


axios.all([getBlogPosts()])
 .then(axios.spread(function(blogResponse) {
    console.log(blogResponse.data);
}));

@James you are correct . you can chain multiple requests as below or you can go for asyn and await options .

 axios.get(...)  // for allPosts
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('Response', response);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM