skip to Main Content

I am trying to make a bunch of axios get calls with this code:

console.log("getting here")
const promises = Data?.stuff.map(async(id: any) => {
      axios.get('http://127.0.0.1:8080/api/v1/stuff/' + id)
        .then(response => {
          console.log(response.data)
          return response.data;
        });
      const tempLesson: any = await Promise.all(promises);
      console.log("never getting here")

but it does not execute until the end. Whats the problem?

3

Answers


  1. Your code are missing return statement and closing brackets

    Your previous code should not compile. I don’t know how the first console.log can run.

    console.log("getting here")
    const promises = Data?.stuff.map((id: any) => { // Removed async
        // Missing return statement
        return axios.get('http://127.0.0.1:8080/api/v1/stuff/' + id)
            .then(response => {
                console.log(response.data)
                
                return response.data;
            })
    }) // Missing }) here
    
    const tempLesson: any = await Promise.all(promises);
    console.log("getting here")
    
    Login or Signup to reply.
  2. You can use axios asynchronously without extra promises

    const promises = Data?.stuff.map(async(id: any) => {
        return await axios.get('http://127.0.0.1:8080/api/v1/stuff/' + id);
    }
    
    Login or Signup to reply.
  3. The Promise.all(promises) should be awaited outside of the .map() function. What Promise.all() does is it takes an array of promises (in your case, an array of Axios requests) and only resolves when all the promises in the array have resolved, or one has rejected.

    so, if you want to do it:

    const promises = Data?.stuff.map((id: any) => {
        return axios.get('http://127.0.0.1:8080/api/v1/stuff/' + id)
            .then(response => {
              console.log(response.data);
              return response.data;
            });
    });
        
    Promise.all(promises)
        .then((results) => {
            console.log("All promises resolved");
            console.log(results);
        })
        .catch((error) => {
            console.log("A promise rejected with error", error);
        });
    

    That’s all.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search