1
async function someFunction() {
  try {
    await Promise.all([
      trendingsSlide.forEach((val) => {
        axios(
          `https://api.themoviedb.org/3/movie/${val}?api_key=${api}`
        );
      }),
    ]).then((val) => {
      console.log(val);
    });
  } catch (err) {
    console.log(err);
  }
}
someFunction();

Why The response is undefined, I tried a lot to fix the problem but it is not working

2 Answers 2

1

Because forEach returns undefined. You wanted map, and also to return the promise from axios from the callback (which you can do implicitly with a concise arrow function rather than one with a {} body):

async function someFunction() {
  try {
    await Promise.all(
      trendingsSlide.map((val) => 
        axios(
          `https://api.themoviedb.org/3/movie/${val}?api_key=${api}`
        )
      )
    ).then((val) => {
      console.log(val);
    });
  } catch (err) {
    console.log(err);
  }
}
someFunction();

You could make it a bit more readable (to me, anyway) by using an async function with map:

async function someFunction() {
  try {
    await Promise.all([
      trendingsSlide.map(async (val) => {
        const val = await axios(
          `https://api.themoviedb.org/3/movie/${val}?api_key=${api}`
        );
        console.log(val);
    });
  } catch (err) {
    console.log(err);
  }
}
someFunction();
Sign up to request clarification or add additional context in comments.

4 Comments

But Why He Return Fullfilled in the console?
Also, no array literal around the map()
@Bergi - Gah! I read right past that in the OP's code.
@mohahmed123 - Because if you pass a non-promise into Promise.all, it treats it as a promise fulfilled with that value. You were effectively doing Promise.all([undefined]).then(...) which will call your fulfillment handler.
0

I don't know why you have used async/await to wait for your response as you're not doing anything after the response was returned.

Promise.all is enough in your case and no need for unnecessary code blocks

function someFunction() {
    const promises = [];
    trendingsSlide.forEach((val) => {
      promises.push(axios(
         `https://api.themoviedb.org/3/movie/${val}?api_key=${api}`
      ));
    })

    Promise.all(promises).then((val) => {
      console.log(val);
    }).catch(console.error);
}

someFunction();

Hope this might help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.