Node.Js 似乎忽略了随机执行中的 await 关键字



我有一个异步函数:

async function getLeads(page) {
return await new Promise(async (resolve, reject) => {
while (true) {
await page.waitFor(1000);
const content = await page.content();
const contentArr = content.split('<div');
const matchedValue = contentArr.filter(
//@ts-ignore
arr =>
arr.search('move;">Remaining records in active lists</div>') !== -1
)[0];
const index = contentArr.indexOf(matchedValue) + 3;
const value = contentArr[index];
const totalLeads = value.split('>')[1].split('<')[0];
if (totalLeads === '-') {
console.log('Leads not ready trying again...');
} else {
resolve(totalLeads);
}
}
reject();
});
}

这个函数在一个更复杂的函数中,但我会简化:

async function scrape() {
console.log('Starting Lead Wait...');
const totalLeads = await getLeads(page);
console.log(`Total Number of leads: ${totalLeads}`);
await page.waitFor(1000);
console.log('Browser closed!');
}

有时这按预期工作,输出为:

Loading page...
Logging in...
Leads not ready trying again...
Leads not ready trying again...
Leads not ready trying again...
Leads not ready trying again...
Leads not ready trying again...
Total Number of leads: 323
Browser closed!

其他时候它似乎忽略了 await 关键字并打印:

Loading page...
Logging in...
Starting Lead Wait...
Total Number of leads: 
Browser closed!
Leads not ready trying again...
Leads not ready trying again...
Leads not ready trying again...
Leads not ready trying again...
Leads not ready trying again...

知道为什么这种不一致的行为吗?

在仔细查看函数执行后,在某些情况下,"totalLeads"解析为未定义的解析没有值的承诺,因为 while 循环中没有中断,即使承诺已解析,while 循环也会继续执行代码。修复了 2 个更改:

if现在是 else if(( 并测试更具体的情况。 在解决后添加了中断。

不过我确实有一个问题,即使包含它的函数已返回,while 循环如何继续执行?

最新更新