簡體   English   中英

在(axios)請求循環之后(嚴格)執行某些東西

[英]Execute something (strictly) after a loop of (axios) requests

我用 axios 發出一個 get 請求,然后結果給了我 N 個 URL,我需要在其中發出 N 個不同的請求來填充字典。 N 個請求的執行不需要是順序的,並且在每次迭代時記錄數據我得到了我想要的,順便說一下,在所有請求完成后我無法訪問字典。 實現這一目標的正確方法是什么?

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

您的代碼沒有等待axios.get(...)解決。

當您有一個沒有awaitasync function 時,這是一個不好的跡象。

以下是它的工作原理:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM