Error in the sequence following Axios subrequest

I am currently working on implementing a search functionality using the Wordpress API. Although I am able to successfully make requests, I am facing an issue where the results are not ordered as expected after my initial request. Let me explain the situation. My initial axios request is for a search operation which returns a list of posts with their titles and IDs. However, within a foreach loop, I am attempting to make subsequent requests to fetch individual posts based on their IDs:

  methods: {
    getSearch: async function () {
      const query = "/search?subtype=post&search=" + this.$route.query.q;
      const response = await this.axios.get(query);
      return response.data;
    },
    getPost: async function (id) {
      const query = "/posts/" + id;
      const response = await this.axios.get(query);
      return response.data;
    },
    getCategorie: async function (id) {
      const query = "/categories?post=" + id;
      const response = await this.axios.get(query);
      return response.data;
    },
    search: async function () {
      await this.getSearch().then((search) =>
        Promise.all(search).then(
          search.forEach(async (tuto) => {
            console.log(tuto.title); // Result in order
            await this.getPost(tuto.id).then((post) => {
              console.log(post.title); // Not the same order
            });
          })
        )
      );

      console.log(this.tutos_search);
    },
  },

Although I suspect it may be related to the usage of async/await functions, I have been unable to identify a solution thus far.

The console output displays:

487
493
480
463
458
Proxy {}[[Handler]]: Object[[Target]]: Array(0)[[IsRevoked]]: false
480
487
458
493
463

As evident from the console log, there is a discrepancy in the ordering between the first and second logs, interspersed with the final console.log message. I am perplexed by this inconsistency as I have included await statements in my code.

For your information, I am using VueJS. Thank you for your assistance.

Answer №1

Thank you everyone for your help, I still have some improvements to make but the code below is functioning!


  methods: {
    fetchSearchResults: async function () {
      const query = "/search?subtype=post&search=" + this.$route.query.q;
      const response = await this.axios.get(query);
      return response.data;
    },
    fetchPost: async function (id) {
      const query = "/posts/" + id;
      const response = await this.axios.get(query);
      return response.data;
    },
    fetchCategories: async function (id) {
      const query = "/categories?post=" + id;
      const response = await this.axios.get(query);
      return response.data;
    },
    searchPosts: async function () {
      const searchResults = await this.fetchSearchResults();

      for (let i = 0; i < searchResults.length; i++) {
        const postId = searchResults[i].id;
        const post = await this.fetchPost(postId);
        const categories = await this.fetchCategories(postId);
        post.categories.length = 0;
        post.categories = categories;
        console.log(post);
      }
    },
  },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

react component failing to update after state change

The layout is not displaying correctly when the state of page changes. Whenever I click on a category link, it verifies if the link exists in the category list. Then, it should update the page state to 'category'. Similarly, clicking on a recipe ...

An empty array is being returned by the Model.find() method after sorting

let query = Tour.find(JSON.parse(queryStr)); if (req.query.sort) { query = query.sort(req.query.sort);//a string 'ratings' } const tours = await query; res.status(200).json({ status: 'success', requestedAt: req.requestTime, ...

Challenging glitch in the JavaScript code

My jQuery code seems to be functioning properly in online text editors like Fiddle and StackOverflow snippets. However, when I try to implement the same code in Brackets or view it on GitHub, the navbar scroll down animation fails to work as expected. You ...

Error: The variable YouTube has not been declared within this context / YouTube API

In my attempt to implement a search using the YouTube Data API, I have come up with the following code. The setup involves an express generated stack with jade. #player script. // 2. This code loads the IFrame Player API code asynchronously. ...

Tips for establishing a connection to a SQL CE database using JavaScript within Internet Explorer

I am currently working on a Browser Plugin that involves storing data in an SQLCE Database locally. My challenge is to display this saved data on a webpage within the browser by connecting to the local database and fetching the values using JavaScript. S ...

I am currently working with a for loop within an object in JavaScript, but there seems to be a problem with one

Here is a function called validator: import validator from "validator"; import isEmpty from "is-empty"; export default function validate(data) { const errors = {}; for (const property in data) { console.log(property); //< ...

JQUERY function fails to execute following the invocation of an array

There is an array named NAME being created. Weirdly, the code seems to be functioning fine for alert('test1') but encounters an issue when reaching alert('test2') $(document).on('submit','form',function() { ...

Using TypeScript's interfaces to push items

Can anyone provide some guidance on working with interfaces in typescript? I currently have the following 3 interfaces: export interface HomeMenu { [name: string]: MenuItem; } export interface MenuItem { title: string; route: string; hom ...

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

Error: The property 'initializeApp' cannot be read because it is undefined

Recently, I decided to integrate Firebase libraries into my Vue project by installing them using npm install firebase. I then proceeded to add these Firebase libraries in my main.js file: import { Firebase } from 'firebase/app' import 'fir ...

Tips for increasing a progress bar as data is being added to a database in PHP when a button is clicked

I attempted to implement this code but faced difficulties. Here is the code snippet I used : <script> $(document).ready(function(){ var $progressbar = $("#progressbar"); $progressbar.show(); $('#uploadForm').on ...

Ensuring the authenticity of dynamic forms

jQuery(document).ready(function(){ $("#submitButton").click(function () { if ( $("#formToSubmit").validationEngine('validate') == true) { $("#formToSubmit").submit(); } }); Utilizing the Validation Engine plugin for jQuery to valida ...

Choose the identical value multiple times from a pair of listboxes

Is there a way to use the bootstrapDualListbox() function to create an input that allows selecting the same value multiple times? I have been searching for a solution to this issue without success. If I have a list like this: <select multiple> <op ...

I am utilizing Vuex to store all of the product details and handle API request queries efficiently

Question regarding Vue/Vuex efficiency and best practices. I am working with an API that returns a paginated data-set of 50 products, which I am storing in a Vuex store. When displaying all products, I iterate over the Vuex store. Now, for individual pr ...

Is there a way for Passportjs to provide an authentication result without automatically redirecting to a different page?

I have implemented user authentication using passportjs. While the official guide demonstrates a redirection operation after authentication, I am looking to receive a JSON object from passport indicating the success or failure of the authentication process ...

Can you help me with sorting asynchronous line points for KineticJS?

For the past couple of days, I've been grappling with a peculiar issue that I found difficult to articulate in the title. The challenge I'm facing involves a KineticJs Line, which contains an array of points (line.attrs.points) represented as ob ...

Can the arrangement of divs be altered solely based on specific browser widths, rather than just for visual appeal?

Imagine having the following HTML structure: <div class="outer"> <div class="inner"> </div> </div> However, under the condition @media (min-width: 890px) and (max-width: 958px), you want it to look like this: <div clas ...

Issue encountered when trying to use Array.sort() method to sort an array of objects

I'm facing an issue sorting an array of objects by a name property present on each object. When utilizing the sort() method with the given code snippet, I encounter the following error: ERROR ReferenceError: b is not defined This is my code block: m ...

What is the best way to locate the elements in the Array that have these particular IDs

This is a challenging logic problem that I've been struggling with. For example, I have an array: ["tech", "review", "howto"]. Along with a larger array containing ids and corresponding texts. ...

Pop-up modal from Bootstrap appearing on top of the page header

I'm working on a website layout where the header always stays on top of everything. However, whenever I add a bootstrap modal that pops up, it ends up covering the header with a grey area. I've attempted to adjust the z-index values for both the ...