Hello. I don’t understand how sending similar requests, but with different parameters, getting all the answers to the same callback then organizing to which request what answer came? Maybe this approach itself is fundamentally wrong? But then how?

I would also like to make a timeout that if within a minute there was no answer, make three more attempts, and if all are unsuccessful, then “surrender” by unsubscribing in console.log and continue working further.

For example, there is a forum where you need to get information about specific users by 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 am in Node.JS not a professional, but just a beginner. Very welcome answer with the code and its explanation. Thank.

    1 answer 1

    Try replacing var with let in the first for loop, then each cUser will be declared at the level of the for {..} block.