问题
'requestingUserIds' is an array, with different ids. Each id belongs to a username in the table 'users'. That's why I want to loop, for each id in the array 'requestingUserIds', the corresponding username into the array 'requestingUserUsernames' and finally log the full array (requestingUserUsernames) into the console. But if I do it outside the then function, only an empty array is output, probably the array I initiated in the beginning.
When i log the array 'requestingUserUsernames' inside the then function in the console, the array gets outputted for each loop pass, but i only want to output the final array.
requestingUserIds.forEach(userId => {
db('users')
.select('username')
.where({id: userId})
.then(rows => {
requestingUserUsernames.push(rows[0].username);
})
.catch(error => console.log(error));
});
console.log(requestingUserUsernames);````
回答1:
try this
const requestingUserUsernames = await Promise.all(requestingUserIds.map(userId =>
db('users')
.select('username')
.where({id: userId})
.then(rows => rows[0].username)));
console.log(requestingUserUsernames);
Make sure it is in an async function
回答2:
requestingUserIds.forEach(userId => {
db('users')
.select('username')
.where({id: userId})
.then(rows => {
requestingUserUsernames.push(rows[0].username);
if (requestingUserUsernames.length == requestingUserIds.length) {
console.log(requestingUserUsernames);
}
})
.catch(error => console.log(error));
This also worked, but im not sure if it is as clean as below.
来源:https://stackoverflow.com/questions/57209251/database-query-in-loop-returns-only-an-empty-array