javascript - 在 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
,那么正确的方法是什么?
解决方案
您可能希望在睡眠后实现重试功能。
如果您没有收到任何响应(其中有数据未定义),请尝试以 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()
推荐阅读
- spring - 控制器方法上的自定义注释以拦截请求和验证
- javascript - 带有数字输入和输出的 Javascript 和 html 表单需要的建议
- json - 使用 CSV 数据集配置加载 JSON 数据
- python - Python 3.6 AttributeError:模块“statsmodels”没有属性“compat”
- python - 按列中的值过滤多头数据帧中的行
- python - 错误:使用 pydocumendb 将数据上传到 Cosmosdb
- git - 如何发现已推送的提交被修改然后再次推送?
- sql - SQL删除重复维护最早/最晚日期
- excel - excel过去90天平均一列
- laravel - 如何覆盖包中的单个函数以供 laravel 内部使用?