简体   繁体   中英

Trying to fetch multiple api in javascript with promise.all and forEach

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

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();

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.

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