[英]Execute something (strictly) after a loop of (axios) requests
I make a get request with axios, then the result give me N urls where i need to make N different requests to populate a dictionary.我用 axios 发出一个 get 请求,然后结果给了我 N 个 URL,我需要在其中发出 N 个不同的请求来填充字典。 The execution of the N requests doesn't need to be sequential and logging data at each iteration i get what i want, by the way I'm not able to access the dictionary after all requests finished.
N 个请求的执行不需要是顺序的,并且在每次迭代时记录数据我得到了我想要的,顺便说一下,在所有请求完成后我无法访问字典。 What's the correct way to achieve that?
实现这一目标的正确方法是什么?
async function myAsyncFuncion() {
let firsturl = "https://www.firsturl.com/something";
let myDict = {};
axios.get(firsturl).then( res => {
const $ = cheerio.load(res.data)
let el_list = $(".someclass");
for(let i=0; i<el_list.length; i++){
let url_ = `https://www.someurl.com/page/${el_list[i]}`;
axios.get(url_).then( res => { let $$ = cheerio.load(res.data);
let list_s = $$("li.someclass");
list_s.each((i,e)=> {
let p = $$(e).attr('data-xxx');
myDict[p] = [];
myDict[p].push($$(e).text());
console.log(myDict[p]); //filled as expected
});
});
}
});
return myDict;
}
myAsyncFuncion().then(res => {console.log(res)}); //dict appears empty here
You're code is not awaiting axios.get(...)
to resolve.您的代码没有等待
axios.get(...)
解决。
It is a bad indication when you have an async
function without await
in it.当您有一个没有
await
的async
function 时,这是一个不好的迹象。
Here is how it could work:以下是它的工作原理:
async function myAsyncFuncion() {
let firsturl = "https://www.firsturl.com/something";
let myDict = {};
const res = await axios.get(firsturl);
const $ = cheerio.load(res.data);
let el_list = $(".someclass");
for(let i=0; i<el_list.length; i++){
let url_ = `https://www.someurl.com/page/${el_list[i]}`;
const res = await axios.get(url_);
let $$ = cheerio.load(res.data);
let list_s = $$("li.someclass");
list_s.each((i,e)=> {
let p = $$(e).attr('data-xxx');
myDict[p] ??= []; // Only when entry doesn't exist yet?
myDict[p].push($$(e).text());
console.log(myDict[p]);
});
}
return myDict;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.