在 NodeJS 中等待数据 return 而不是休眠
Waiting for data to return in NodeJS instead of Sleeping
所以我正在编写一个需要我确认电子邮件地址的小抓取工具,但是我使用的 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()
所以我正在编写一个需要我确认电子邮件地址的小抓取工具,但是我使用的 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()