简体   繁体   English

节点多个获取请求循环传递到数组

[英]Node multiple get requests loop pass into array

I have a get request in which lies a loop of get requests. 我有一个get请求,其中包含一个get请求循环。 They pass back data that I want to add to an array, What would be the best way to structure my code with maybe promises to be able to pass the values back from inside the loop and when they have all finished be able to console.log the data? 它们将我要添加到数组的数据传递回去。这是构造代码的最佳方法,它可能承诺能够将值从循环内部传递回,并且当它们全部完成后就可以进行console.log了。数据?

app.get('/outer', (res, req) => {
    let url = 'https://samplejson.json';
    https.get(url, (response) => {
      response.on('data', (data) => {
        let parsed = JSON.parse(data);
        let collected = [];
        parsed.forEach((myId) => {


                let innerUrl = `https://samplejson/${innerId}.json`;
                https.get(innerUrl, (innerResponse) => {
                    innerResponse.on('data', (innerData) => {
                        let parsedInner = JSON.parse(innerData);
                        //console.log(JSON.stringify(parsedInner,null,2));
                        let collect = parsedInner.title.trim().split(' ');
                        collect.forEach((w) => {
                            //console.log(w); // works
                            collected.push(w);
                        });
                    }, (err) => res.status(400).send(err));
                 } , (err) => res.status(400).send(err));


        }, (err) => res.status(400).send(err));
        console.log('ending'); // never shown ?
        console.log(collected); // never shown ?
      });
  }, (err) => res.status(400).send(err));
}, (err) => {
    res.status(400).send(err);
});

My issue is that the collected array never gets shown, I am guessing because the requests can never send back the data? 我的问题是收集到的数组永远不会显示,我猜是因为请求永远无法发回数据?

So what is the best way to break down my code and do it the right way? 那么分解我的代码并以正确的方式做事的最佳方法是什么? Thanks 谢谢

The code you've posted above initiate multiple async requests in parsed.forEach() , but console logs the array before the requests have finished. 您上面发布的代码在parsed.forEach()启动了多个异步请求,但控制台在请求完成之前记录了阵列。 Thus there are no data to display. 因此,没有要显示的数据。 I've posted a suggested fix below 我在下面发布了建议的修复

The code has been made more readable by using the request-promise library. 使用request-promise库使代码更具可读性。

app.get('/outer', (res, req) => {
  return requestPromise({
      url: 'https://samplejson.json',
      method: 'GET',
      json: true
    })
    .map((myId) => {
      return requestPromise({
          url: `https://samplejson/${myId}.json`,
          method: 'GET',
          json: true
        })
        .then((innerData) => {
          return innerData.title.trim().split(' ');
        });
    })
    .reduce((accumulated, current) => {
      return accumulated.concat( current );
    }, [])
    .then((collected) => {
      console.log("Collected into a flattened array:", collected);
    })
    .catch((error) => {
      res.status(400).send(error);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM