Javascript 检查所有要完成的请求
我目前正在使用一个scraper异步获取多个URI。 我的问题是,我想等待所有的响应被处理,但我不知道如何找出每个响应何时被处理 带有“Done!”的最后一个日志甚至在响应返回之前运行 谢谢你的帮助 Xaver:)Javascript 检查所有要完成的请求,javascript,node.js,asynchronous,request-promise,Javascript,Node.js,Asynchronous,Request Promise,我目前正在使用一个scraper异步获取多个URI。 我的问题是,我想等待所有的响应被处理,但我不知道如何找出每个响应何时被处理 带有“Done!”的最后一个日志甚至在响应返回之前运行 谢谢你的帮助 Xaver:) const rp=require('request-promise'); const cheerio=需要(“cheerio”); //功能 函数getData(arr){ //使用循环获取每个地址 for(设i=0;i{ console.log('successfetchingda
const rp=require('request-promise');
const cheerio=需要(“cheerio”);
//功能
函数getData(arr){
//使用循环获取每个地址
for(设i=0;i{
console.log('successfetchingdata of:'+arr[i])
console.log('现在格式化!')
//格式化我的数据。。。
})
.catch((错误=>{
//错误处理
控制台错误(错误消息)
info(`errDelay/1000}秒内重试`)
设置超时(()=>{
rp(opt)
},延迟);
}))
}
//这应该在每个请求格式化之后运行,但当前它在请求完成之前运行,但不会
console.log('Done!')
}
getData()```
就是你想要的
Promise.all(arr.map((u,i)=>{
//设置我的选项
让opt={
方法:“GET”,
//在url中插入索引以在每个循环中获取不同的站点
uri:`https://example.de/${i}`,
标题:{
Referer:'example.de',
},
resolveWithFullResponse:true,
//加载jquery/cherrio
转换:功能(主体){
返回车重(车身);
}
};
//运行请求
返回rp(opt)
。然后($)=>{
console.log('successfetchingdata of:'+arr[i])
console.log('现在格式化!')
//格式化我的数据。。。
})
.catch((错误=>{
//错误处理
控制台错误(错误消息)
info(`errDelay/1000}秒内重试`)
设置超时(()=>{
rp(opt)
},延迟);
}))
}).然后(()=>console.log('done'))
您可以使用带有try-catch块的async wait来处理错误
异步函数getData(arr){
for(设i=0;i感谢您的帮助,我已经尝试过使用承诺,但我不知道如何在使用for循环时创建承诺收集数组中的承诺,然后使用
Promise.all
在`setTimeout(()=>{rp(opt)},errDelay);`设置此超时将打破承诺链
const rp = require('request-promise');
const cheerio = require('cheerio');
//The function
function getData(arr) {
// Using loop to fetch every adress
for (let i = 0; i < arr.length; i++) {
//Setting my options
let opt = {
method: 'GET',
//Inserting index into url to get different site every loop
uri: `https://example.de/${i}`,
headers: {
Referer: 'example.de',
},
resolveWithFullResponse: true,
//Loading jquery/cherrio
transform: function (body) {
return cheerio.load(body);
}
};
//running the request
rp(opt)
.then(($) => {
console.log('Success fetching Data of : ' + arr[i])
console.log('Now formatting!')
//formatting my data ...
})
.catch((err => {
//err handling
console.error(err.message)
console.info(`Retrying in ${errDelay / 1000}sec`)
setTimeout(() => {
rp(opt)
}, errDelay);
}))
}
//This should run after every request is formatted but currently it runs before the requests are done BUT IT DOESN'T
console.log('Done!')
}
getData()```
async function getData(arr) {
for (let i = 0; i < arr.length; i++) {
let opt = {
method: 'GET',
uri: `https://example.de/${i}`,
headers: {
Referer: 'example.de',
},
resolveWithFullResponse: true,
transform: function (body) {
return cheerio.load(body);
}
};
try {
const response = await rp(opt);
console.log('Success fetching Data of : ' + arr[i])
console.log('Now formatting!')
}
catch (e) {
console.error(err.message)
console.info(`Retrying in ${errDelay / 1000}sec`)
setTimeout(() => {
rp(opt)
}, errDelay);
}
}
}