0

[enter image description here][1]I have problems with async/await. in consolelog 1 ,consolelog 2 and consolelog 3 thanks for more

const getAnimEpisodesProm = async (URL) => {
return new Promise(async(resolve, reject) => {
    const html = await http.loadHtml(URL);
    const $ = cheerio.load(html.data);
    const animEpisodes = [];
    $("ul[id=episode_related]").find("a").each(async (_, element) => {
        const Url = BUrl + $(element).attr("href").trim();
        episodeId = $(element).find(".name").text().split(" ")[2];
        await getEpisodeX(Url,episodeId).then(val => {
            animEpisodes.push(val);
            console.log(animEpisodes.length)
        })
    })
    console.log(animEpisodes.length, "here")
    resolve(animEpisodes);
});

}

outpute of code

0 'here'
[]
1
2
3
4
5
Ayoub Mellouk
  • 31
  • 1
  • 4
  • Try `console.log('one:',episodeId),console.log('two:',episodeId),console.log('three:',episodes)` and see that 'three' logs first. Your problem is best explaned in this [question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – HMR Jan 25 '19 at 13:45
  • Regarding your latest edit, avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 27 '19 at 14:38

1 Answers1

0

welcome to Stack Overflow, you cannot asynchronously mutate an array and expect that array to be set before the promise is resolved/rejected.

You can re write the code in the following way:

const animEpisodesPromise = Promise.all(
  Array.from($('ul[id=episode_related]').find('a'))
    .map((_, element) => [element, element.href]) //return anchors and their href attribute
    .filter(([element, href]) => !!href) //remove anchors that have no href attribute
    .map(([element, href]) => {
      const Url = href.trim();
      episodeId = $(element)
        .find('.name')
        .text()
        .split(' ')[2];
      return getEpisodeX(Url).then((val) => {
        console.log(episodeId); //consolelog 2
        return {
          episodeId,
          links: val,
        };
      });
    }),
);
animEpisodesPromise.then((animEpisodes) =>
  console.log('resolved', animEpisodes),
); //consolelog 3
return animEpisodesPromise; //returns promise of animEpisodes
HMR
  • 37,593
  • 24
  • 91
  • 160
  • `5 4 3 2 1 (node:115308) UnhandledPromiseRejectionWarning: TypeError: [object Object] is not iterable.... 1 1 1 1 1` – Ayoub Mellouk Jan 25 '19 at 14:24
  • 1
    @AyoubMellouk You can try `Array.from($('ul[id=episode_related]').find('a')).map` instead, different versions of jQuery may not produce the same result – HMR Jan 25 '19 at 14:32
  • TypeError: Cannot read property 'trim' of undefined – Ayoub Mellouk Jan 26 '19 at 21:00
  • @AyoubMellouk Updated anser, looks like some of your anchors don't have an href attribute. I filter out these anchors. – HMR Jan 28 '19 at 10:06