Issue in returning data retrieved from DB queries called in the loop
Let's start with the general rule for using promises:
Every function that does something asynchronous must return a promise
Which functions are these in your case? It's getPrayerInCat
, the forEach
callback, and Prayer.find
.
Hm, Prayer.find
doesn't return a promise, and it's a library function so we cannot modify it. Rule 2 comes into play:
Create an immediate wrapper for every function that doesn't
In our case that's easy with Q's node-interfacing helpers:
var find = Q.nbind(Prayer.find, Prayer);
Now we have only promises around, and do no more need any deferreds. Third rule comes into play:
Everything that does something with an async result goes into a
.then
callback
…and returns the result. Hell, that result can even be a promise if "something" was asynchronous! With this, we can write the complete callback function:
function getPrayerCount(data2) {
var id = data2.id;
return find({prayerCat:id})
// ^^^^^^ Rule 1
.then(function(prayer) {
// ^^^^^ Rule 3
if (!prayer)
data2.prayersCount = 0;
else
data2.prayersCount = prayer.length;
return data2;
// ^^^^^^ Rule 3b
});
}
Now, we have something a bit more complicated: a loop. Repeatedly calling getPrayerCount()
will get us multiple promises, whose asynchronous tasks run in parallel and resolve in unknown order. We want to wait for all of them - i.e. get a promise that resolves with all results when each of the tasks has finished.
For such complicated tasks, don't try to come up with your own solution:
Check the API of your library
And there we find Q.all
, which does exactly this. Writing getPrayerInCat
is a breeze now:
function getPrayerInCat(data) {
var promises = data.map(getPrayerCount); // don't use forEach, we get something back
return Q.all(promises);
// ^^^^^^ Rule 1
}
If we needed to do anything with the array that Q.all
resolves to, just apply Rule 3.
php function not returning all results from a MySQL query in a foreach
At the moment you are just returning the last data row. Change your code like this to return an array of all your rows from that function:
$rows = array()
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$rows[] = $new_data;
}
return $rows;
This way every row returned from the database will be added to an array named $rows
. At the end you have to return your new array.
Non stop queries being called even though there is no loop Javascript
As I can see you make request whenever component is render. For react you must wrap your request in useEffect
hook with empty deps array and use useState
for dataArray
it prevents your component to run request after each rerender
import {useEffect, useState} from 'react';
const [dataArray, setDataArray] = useState([]);
useEffect(() => {
const databaseData = {
method: 'GET',
url: 'http://localhost:8000/data'
}
axios.request(databaseData).then((response) => {
console.log(response.data)
setDataArray(response.data);
}).catch((error)=>{
console.error(error)
})
}, [])
PHP loop not returning all possible MySQL query results
I think it's a logical error;
when you defined $propertyinfo=array(); it's size is 0, therefore the code withing the block of
for ($l =0; $l< count($propertyinfo); $l) will only start running after some values has been assigned to $propertyinfo.
Stuck with the same values when looping through database rows
Based on the comments on my question, I ended up with the following code:
$users_get = mysqli_query($conn,"SELECT a.id, SUM(b.number) AS number FROM users AS a INNER JOIN users_numbers AS b ON a.id = b.userid GROUP BY a.id ASC");
$loop1 = 0;
while($users_items[] = mysqli_fetch_array($users_get){
echo "ID: ".$users_items[$loop1]['id']." - Num total: ".$users_items[$loop1]['number']."<br />";
$loop1++;
}
The echo inside the while is only for testing purposes. When I run this, it displays a nice list with all the user IDs and the sum of each users numbers.
Related Topics
What Is Meant by 'First Class Object'
Get String in Yyyymmdd Format from Js Date Object
JavaScript - Get Array of Dates Between 2 Dates
Invariant Violation: Objects Are Not Valid as a React Child
Best Way to Iterate Over an Array Without Blocking the Ui
Call Static Methods from Regular Es6 Class Methods
When Does Reflow Happen in a Dom Environment
Assigning Prototype Methods *Inside* the Constructor Function - Why Not
How to Mock Functions in the Same Module Using Jest
Webdriver Click() VS JavaScript Click()
Es6 Modules: Export Single Class of Static Methods or Multiple Individual Methods
How to Get the Size of a JavaScript Object
Truncate Number to Two Decimal Places Without Rounding
Iframe Src Change Event Detection
Asynchronous for Cycle in JavaScript