首页 > 解决方案 > 在 NodeJS 中等待数据返回而不是休眠

问题描述

所以我正在编写一个需要我确认电子邮件地址的小抓取工具,但是我使用的 API 在收到电子邮件后可能会在几秒钟内不更新。

我正在使用的当前方法是这样的:

//wait for page 3 to finish loading
await Promise.all([
    page.waitForNavigation({ waitUntil: 'load' }),
    page.click('#submitbutton'),
]);

//sleep so we can make sure we receive the email.
await Apify.utils.sleep(5000);

//get emails
try {
    emails = await getEmails(userProfile.email); //this is just an Axios request/response.
} catch (error) {
    return res.send(error_response('email_api_failed'));
}

emails.data.forEach(obj => {
    //perform magic here on emails..
});

但是我经常会遇到错误emails.data.forEach is not a function,那么正确的方法是什么?

标签: javascriptnode.jssleep

解决方案


您可能希望在睡眠后实现重试功能。

如果您没有收到任何响应(其中有数据未定义),请尝试以 X 毫秒的间隔再次请求。

它可以很简单:

function getEmails(retries = 5) {
  return new Promise(async (resolve, reject) => {
    while (retries-- > 0) {
      await Apify.utils.sleep(5000)
      emails = await getEmails(userProfile.email)

      if (emails.data) {
        return resolve(emails.data)
      }
    }

    resolve('No Data')
  })
}

const data = await getEmails()

推荐阅读