简体   繁体   English

如何获得异步/等待 function 的结果?

[英]How to get the result of async / await function?

I would like to return an object from the the async / await function A to pass it to another function.我想从异步/等待function A返回一个 object 以将其传递给另一个 function。

Currently what I get as a result is Promise{ <pending> }' or undefined.目前我得到的结果是Promise{ <pending> }'或未定义。

function A: function

const parseRss = data => data.forEach(rssLink => {
    const getFeed = async () => {
        try {
            const feed = await rssParser.parseURL(rssLink.rss);
            const emailContent = {
                emailBody: {
                    title: feed.title,
                    content: []
                }
            }

            feed.items.forEach(item => {
                feedObj.emailBody.content.push(`${item.title} : ${item.link}`)
            });
            return emailContent;
        } catch (e) {
            console.error(e);
        }
    };
    return (async () => {
        return await getFeed();
    })();
});

Function B: Function B:

    try {
        const data = await getDataWithRss();
        const emailData = await parseRss([{rss:'http://reddit.com/.rss'}]); // emailData is undefined
       return formatEmail(emailData);
    } catch (error) {
        console.log(error);
    }

How do I return emailContent from function A to use it in function B?如何从 function A 返回emailContent以在 function B 中使用它?

Thanks!谢谢!

Since you made getFeed as async, no need another async.由于您将getFeed设为异步,因此不需要另一个异步。 You are looping through, so return an array of promises.您正在循环,因此返回一组承诺。 Once the you call use Promise.all to resolve.一旦你打电话使用Promise.all来解决。 Since there could be multiple urls to fetch.因为可能有多个 url 要获取。

const parseRss = (data) =>
  data.map((rssLink) => {
    const getFeed = async () => {
      try {
        const feed = await rssParser.parseURL(rssLink.rss);
        const emailContent = {
          emailBody: {
            title: feed.title,
            content: [],
          },
        };

        feed.items.forEach((item) => {
          feedObj.emailBody.content.push(`${item.title} : ${item.link}`);
        });
        return emailContent;
      } catch (e) {
        console.error(e);
      }
    };
    return getFeed();
  });
  try {
    const data = await getDataWithRss();
    const emailData = await Promise.all(parseRss([{rss:'http://reddit.com/.rss'}])); // emailData is undefined
   return formatEmail(emailData);
} catch (error) {
    console.log(error);
}

await will not work inside a forEach loop. await 在 forEach 循环中不起作用。 Use a for...in loop instead.请改用 for...in 循环。

actually, getFeed() is not necessary inside inner scope, you can use async in map callback:实际上,在内部 scope 中不需要 getFeed(),您可以在 map 回调中使用异步:

const parseRss = data => data.map(async rssLink => {
    const feed = await rssParser.parseURL(rssLink.rss);
    const emailContent = {
        emailBody: {
            title: feed.title,
            content: []
        }
    };

    feed.items.forEach(item => {
        feedObj.emailBody.content.push(`${item.title} : ${item.link}`)
    });

    return emailContent;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM