"What is the best way to indicate that the most recent web service call has finished in a Javascript

I am trying to execute the following code block:

this.setState({ // <------------ REF 1
  pages: pages
});

only after all

axios.get('https://graph.facebook.com/v5.0/' + page.id + '/events?access_token=' + accessToken)
requests have finished. REF 2

How can I achieve this in Javascript?

let accessToken = response.accessToken
axios.get('https://graph.facebook.com/v5.0/me/accounts?fields=id,name&access_token=' + response.accessToken)
.then(response => {
console.log("test")
let pageList = response.data.data.map(page => {
  console.log("page " + page.id + " " + page.name);
  this.setState({
    page: response.data.data
  });

  var pages = {}; // <------------ REF 2
  axios.get('https://graph.facebook.com/v5.0/' + page.id + '/events?access_token=' + accessToken)
  .then(response => {
    console.log("test 2");
    var events = {};
    let eventList = response.data.data.map(event => {
      console.log("event " + event.id + " " + event.name);
      events[event.id] = event.name;
    });
    pages[page.id] = [page.name, events];
  })

  this.setState({ // <------------ REF 1
    pages: pages
  });
})
})

Answer №1

If you want to ensure that all Promises are completed before updating the state, one approach is to use Promise.all. However, be aware that if one promise rejects, it will cancel all other requests. To handle this scenario, we include .catch(e => e) which simply catches any rejection and passes it to Promise.all as if the promise had resolved.

By combining this with the await keyword, we can wait for Promise.all to resolve, then iterate over the results to update the state using setState or any desired method.

let accessToken = response.accessToken;
axios
  .get(
    "https://graph.facebook.com/v5.0/me/accounts?fields=id,name&access_token=" +
      response.accessToken
  )
  .then(async pagesResponse => {
    console.log("test");
    let promisesArray = pagesResponse.data.data.map(async page => {
      console.log("page " + page.id + " " + page.name);
      this.setState({
        page: response.data.data
      });

      return axios
        .get(
          "https://graph.facebook.com/v5.0/" +
            page.id +
            "/events?access_token=" +
            accessToken
        )
        .catch(e => e);
    });

    const responses = await Promise.all(promisesArray);
    var pages = {}; // <------------ CODE 2
    responses.forEach((response, i) => {
      console.log("test 2");
      var events = {};
      let eventList = response.data.data.map(event => {
        console.log("event " + event.id + " " + event.name);
        events[event.id] = event.name;
      });
      const page = pagesResponse.data.data[i];
      pages[page.id] = [page.name, events];
    });

    this.setState({
      // <------------ CODE 1
      pages: pages
    });
  });

I hope this explanation clarifies things! Feel free to reach out if you need further assistance.

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

I'm experiencing a problem with my React application where errors are not being shown in the browser. Instead

https://i.sstatic.net/FTMz7.png Why is React only displaying an empty screen instead of showing errors like on my instructor's system? https://i.sstatic.net/QCbgG.png How can I resolve this issue? EDIT: While I can see the error in the console and ...

Best way to eliminate empty options from dropdown and ensure that required validation is functioning in AngularJS?

My dropdown is populated with owners from the owners data, but it includes an extra blank option. I need to eliminate this blank option. However, when I make the necessary changes to remove it, the required validator stops working properly. <md-input-c ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

show various commands and outcomes of the getElementsByClassName() function

Can someone help me figure out how to use the "getElementsByClassName() Method" in JavaScript to change or display different colors? I am trying to change the background color to blue for the class "ex" and red for the class "example", but it's not wo ...

Handlers for event(s) not triggering on video element

In my NextJS application, I have implemented a feature to display a video file using the video element. I have added multiple event handlers to the video element: <video className='video-player' controls={true} preload='metadata&apo ...

What is the best way to implement a scrollbar in a specific div rather than the entire window?

Hey everyone! So, I have this window in electronJS with a div where I'm dynamically adding elements using Javascript and the function --> document.createElement('section'). Here's the loop in Javascript to add these elements: for ( ...

Ensure to verify the presence of a null value within the ngFor iteration

I have a webpage where I am displaying information in buttons. These buttons show various objects from a list along with their corresponding fields (e.g. object.name, object.age, etc.). Sometimes, one of those fields is null. How can I check if a value is ...

Having trouble getting the navigation function to work correctly for my ReactJS image slider

I am looking to create a simple image slider that contains 3 images in an array. I want to be able to navigate through the slider using just one function that can move back and forth between images. If you click "next" on the last image, it should bring ...

How can you use jQuery to remove a class from an element after a specified period of time?

After updating a record in the database, I plan to make modifications using an AJAX request. Once that is done, I will dynamically add a class to the rendered div by utilizing the addClass method. The class being added (we'll refer to it as colored) c ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

What Causes the Misalignment Between My Image and Text?

I am trying to randomly select a slide from the list of slides when the page loads, and then display it in the hero section of a website. However, I am facing an issue where the Image seems to be out of sync with the Text & Button (for example, displaying ...

Ways to activate flashlight on mobile using React.Js

Is it possible to control the torch light of a mobile device by toggling a button? https://i.stack.imgur.com/x9nIf.png <IconButton onClick={() => setFlashOn(!flashOn)} style={{ position: "absolute", right: 80, top: 20, zIndex: ...

Stopping a function when another function is invoked in JavaScript

I've been immersing myself in the search for a way to halt one function if another is called or triggered in JavaScript. Initially, I believed it to be unattainable, but I'm open to having my perspective changed. My current focus lies within a t ...

Stripping the prefix from a string using the .split function leads to an error message stating "Unexpected

When dealing with a string containing a unique prefix, I attempted to separate it into an array after the backslash character "\" by using the split function. Here is the string: i:0#.w|itun\allepage_fg This was my approach: function claimOrder ...

Explore creating a dial number using React

Hey there, I'm currently working on developing a component. Just to clarify, I am not using react-native for this project. Instead, I would like to utilize React to scroll a number similar to how an image scrolls. The goal is to have the number smoo ...

jquery for quick search

<form method="post" action="search.php"> Commence search: <input id="search" type="text" size="30" > <div id="search_results"></div> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script src="//code. ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

Javascript Solution for Testing Palindromes in a Linked List

I recently researched the solution for a palindrome problem using Javascript. There is one particular line of code that I am struggling to comprehend, and I'm hoping someone can shed some light on it for me. Here is the code snippet in question: thi ...