Firstly I appreciate that there are many answers out there explaining this topic but I just can't understand it at the moment.
I want to loop through a JavaScript object I have created and then perform various actions like making a request to an API and then storing some data in Redis.
This is what I have so far
const params = { "handle1": { "screen_name": "handle1", "hash_tag": "#hashtag1"},
"handle2": { "screen_name": "handle2", "hash_tag": "#hashtag2"} }
for (const k of Object.keys(params)) {
console.log("Searching for " + params[k]['screen_name'])
client.get('statuses/user_timeline', { screen_name: params[k]['screen_name']})
.then(function (tweets) {
for (const key of Object.keys(tweets)) {
const val = tweets[key]['text'];
if(val.includes(params[k]['hash_tag'])) {
console.log("Found")
r_client.hset(params[k]['screen_name'], 'tweet_id', tweets[key]['id'], 'tweet_text', tweets[key]['text'], function (err, res) {
console.log(res)
});
r_client.hgetall(params[k]['screen_name'], function(err, object) {
console.log(object);
});
}
}
r_client.quit();
})
.catch(function (error) {
throw error;
});
}
When I run this the output is as follows
Searching for handle1
Searching for handle2
Found
0
{ tweet_id: '123456789',
tweet_text: 'text found in tweet' }
Found
undefined
undefined
So straight away I have a problem in that the first loop hasn't event finished and it's moved onto the second loop.
I would like to run this in sequential order (if that's the best way), but more importantly I was hoping someone could break down my code and explain how I should be approaching this to have it run correctly.