Retrieval from the server. How to process each answer separately?


  • QA Engineer

    Hello. I don't understand how to send similar requests, but with different parameters, getting all the answers to the same collbek and then organising what kind of answer came for? Maybe that's not the right thing to do. But how do we do that?

    I would also like to make sure that if there was no answer in a minute, three more attempts were made, and if all failed, then to give up in console.log and continue to work further.

    For example, there is a forum that needs information about identified users on id:

    var https = require("https");
    

    users = [{
    id: 5
    }, {
    id: 16
    }, {
    id: 30
    }, {
    id: 7
    }, {
    id: 1085
    }, {
    id: 800
    }, ];

    for (var cUser in users) {

    https.get("example.com/api/users?id=" + users[cUser].id, function(resp) {

    resp.setEncoding('utf8');
    
    var str = '';
    resp.on('data', (chunk) => {
      str += chunk;
    });
    
    resp.on('end', () => {
      var recieved = JSON.parse(str);
      for (var attr in recieved) {
        users[cUser][attr] = recieved[attr];
      }
    
      /*  Я так понимаю, что это выполняется как только пришел ответ,
       *   поэтому значение cUser уже изменилось. Но как его сохранить?
       *   _________________________________________________________________
       *
       *   Что примерно присылает сервер:
       *   {id:1,joined:1219448281,status:0,raiting:90000,postcount:136}
       */
    
    });
    

    });
    }

    /* Ожидания: | Реальность:

    •                        |
      
    • >console.log(users); | >console.log(users);
    •                        |
      
    • [ | [
    • {                      |     {id: 5},
      
    •   id: 5,               |     {id: 16},
      
    •   joined: 1219449600,  |     {id: 30},
      
    •   status: 2,           |     {id: 7},
      
    •   raiting: 35245,      |     {id: 1085},
      
    •   postcount: 2304      |     {id: 800},
      
    • },                     |   ];
      
    • {                      |
      
    •   id: 16,              |
      
    •   joined: 1234569405,  |
      
    •   status: 4,           |
      
    •   raiting: 1023,       |
      
    •   postcount: 176       |
      
    • },                     |
      
    • ... и так далее        |
      
    • ]; |
      */

    I'm in Node. JS is not a professional, but a starter. The answer to the code and his explanation is very welcome. Thank you.



  • Try to replace var by let in the first cycle for, then each cUser will be declared at the level of the block for {...}.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2