Hi Replit Community!
I’m working on a Node.js repl at the moment and now I’m trying to get all users’ actions on the server side, sort them by date, and send the first 6 actions to client (as a response to client’s request). The only problem I’m facing is a nested-structure inside a nested structure, involving two for-loops (or any other loop that can iterate through arrays, and is async-friendly) and two async functions to get data from Replit’s built in database.
When running the code below, I end up returning an empty array (given_data). A small research has shown that such happens because of async functions, which run after I send the response (as I mentioned before, the response appears to be an empty array). My attempt of adding .then() instructions failed because of nested code.
Is there a way to solve this problem? Maybe I should somehow split the whole procedure into smaller pieces to avoid nested constructions? My attempts and actions’ description is shown below:
var given_data = [];
var currArt = {};
db.list().then(keys => {
for (var i = 0; i < keys.length; i++) {
db.get(keys[i]).then((value) => {
for (var j = 0; j < value.actions.length; j++) {
if (["false", false].includes(value.actions[j].action_hidden)) {
currArt = structuredClone(value.actions[j]);
currArt.author_name = value.name;
given_data.push(currArt);
}
}
return given_data
})
} // res.json(given_data);
})
Here’s the example of an object with user’s data:
{
name: 'name',
email: 'hyhyh@g.yu',
password: 'coolpass',
actions: array
}
(action is an array of objects)
Here’s the example of an action:
{
title: 'idk smth',
today: '16.06.2023',
fullToday: '16.06.2023 13:08:17',
image: string,
header: string,
type: array,
content: array,
author_email: 'q@w.e',
action_hidden: false
}
(type and content are arrays of strings)
Thanks!