JavaScript中的异步功能

时间:2019-01-25 13:39:00

标签: javascript async-await es6-promise

[在此处输入图片描述] [1]我在异步/等待方面遇到问题。 在consolelog 1,consolelog 2和consolelog 3中 谢谢你更多

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

}

代码输出

0 'here'
[]
1
2
3
4
5

1 个答案:

答案 0 :(得分:0)

欢迎使用Stack Overflow,您不能异步更改数组并期望在解决/拒绝承诺之前设置该数组。

您可以通过以下方式重新编写代码:

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