How Can I Reduce The Amount Of Memory My Node.js Application Uses?
I'm fairly new to Node.js and Javascript in general. (I'm new to StackOverflow as well!) Recently, I wrote a Node.js application that eats up way too much memory. I've read that se
Solution 1:
You are continually calling timeout without waiting for the fetch inside cloud_check 3 if statement to complete. I would change the code a bit to make it more readable and wait for this fetch to complete since it seems you depend on information from that call to set the next state of cloud_check. If that call takes longer than your timeout time then you would be stacking up a lot of functions.
I would break out the code into three functions
getCount --> fetches count from api updateChecks --> updates the cloud checks timeout --> Runs your timeout loop
Here is a little bit of cleanup to get you started. But make sure to take a look on how you can make your code more readable and reusable.
asyncfunctiongetCount(username) {
var res = awaitfetch(`https://api.scratch.mit.edu/users/${username}/messages/count`);
var data = res.json()
if(!data.code) {
return data.count;
}
thrownewError(`ERROR - The user ${username} could not be found!`)
}
asyncfunctionupdateChecks() {
var cloud_check = cloud.get('☁ checkMessage')
if (cloud_check > 0){
if (cloud_check == 1){
cloud.set('☁ checkMessage', 2)
} elseif (cloud_check == 2){
idle_counter++
if (idle_counter > 5){
cloud.set('☁ checkMessage', 0)
idle_counter = 0
}
} elseif (cloud_check == 3){
var username = decode(cloud.get('☁ message'))
try {
var count = awaitgetCount(username)
message = encode(`success.${count}`)
console.log(`SUCCESS - Successfully retrieved the message count (${count}) for the user ${username} !`)
} catch(e) {
message = encode("error.user not found")
console.log(e.message)
}
cloud.set('☁ message', message)
cloud.set('☁ checkMessage', 4)
idle_counter = 0
} else {
idle_counter++
if (idle_counter > 5){
cloud.set('☁ checkMessage', 0)
idle_counter = 0
}
}
}
}
asyncfunctiontimeout() {
setTimeout(async () => {
awaitupdateStates();
timeout();
}, 2000);
}
Post a Comment for "How Can I Reduce The Amount Of Memory My Node.js Application Uses?"