this is my first stackoverflow post. In this NodeJS app, the objective is to get the max value of memory avaible from a IP's pool. I know that I can use the function obtainMemory with a callback but idk how to use in this scenario.
decide(){
for(var i=0;i < raspberrys.length;i++ ){
let ip = raspberrys[i];
let freeSpace = this.obtainMemory(ip);
console.log(freeSpace);
}
},obtainMemory(ip){
https.get('http://'+ip+':3030/memory', (response)=>{
let data='';
response.on('data', (chunk) =>{
data+=chunk;
});
response.on('end',()=>{
let obj = JSON.parse(data);
console.log(obj.free );
return obj.free;
})
}).on('error',(error)=>{
console.log(error);
});
}
For example if i have 2 raspberrys with 2GB and 1MB, I have to return the IP of the first raspberry. Thanks.
Just to make it easier I would transform the get into a promise. You can do that installing some library like got, node-fetch or axios. If you have access to node 17.5 you can use the, now native, fetch you can see how here. I made a promisified version of get too:
const get = (url) => {
return new Promise((resolve, reject) => {
let data = ""
const req = https.get(url, (res) => {
res.on("data", (chunk) => (data += chunk))
res.on("error", (err) => reject(err))
res.on("end", () => {
data = JSON.parse(data)
return resolve(data)
})
})
req.on("error", reject)
req.end()
})
}
You can find a more complete version here.
using it your code:
async function decide() {
// get all raspberrys free memory
const freeMemories = await Promise.all(raspberrys.map(obtainMemory))
// find which one has the biggest memory
const { ip } = freeMemories.reduce(
(prev, curr) => {
if (prev.memory < curr.memory) prev = curr
return prev
},
{ memory: 0 }
)
console.log(ip)
}
async function obtainMemory(ip) {
const ipAddress = `http://${ip}:3030/memory`
const { free } = await get(ipAddress) // using the get function that I defined
return { ip, free }
}