I have an array of values, I need to loop through those to run a function based on a value I get from a textbox.
My code:
<label for="truck">Truck:</label>
<input type="text" id="truck" name="truck">
<button type="button" id="myButton">Click Me!</button>
const truckBtn = document.getElementById("myButton");
const truckID = document.getElementById("truck");
truckBtn.addEventListener("click", () => {
let arrs = ["one", "two", "three"];
for (const arr of arrs) {
axiosFunction(arr, truckID.value).then(d=> {
console.log(d.data);
if (d.data.length > 0) {
// do something
} else alert("Not Found");
});
}
});
So d.data
if truckID.value
matches what I need the response is:
[]
[]
[{...}]
That’s when it goes into the if
statement.
The else is when:
if truckID.value
does not match what I need the response is:
[]
[]
[]
My issue is when I have the else
, it goes to the else even when there is match. Is there way to write an if statement when the length of the array is greater than 0 for at least 1 iteration? And do the else if all the iterations return a length of 0?
4
Answers
Make the callback an async function so you can use
await
. Then you can set a variable based on whether any of the calls return something.It would be ideal if you could rewrite the API behind your
axiosFunction
to take all threearr
values and return a batch, so you’re not making multiple round-trips. But assuming you can’t do that, and you’re okay with waiting for all the round-trips to return (otherwise you can’t know whether they all returned empty), you can usePromise.all()
to wait until they’re all resolved.This code uses
find
assuming you’re only expecting one valid result. You could tweak it to usefilter
if there might be several.This also depends on how you intend on looping through the array – do want to:
Your example can be extended by using
break
once you find the match:Notice the
break
inside the condition when the match is found – this will prevent any subsequent calls toaxiosFunction
, which may or may not be what you want.Below are a few ways of handling the calls depending on whether you want to wait for each call, get the first matching result, or get all the matching results, using
async / await
andArray.map
:As you are making multiple requests with
axiosFunction
, you first need to resolve those promises, usingPromise.allSettled()
orPromise.all()
.Then, you can use
Array.prototype.some()
orArray.prototype.every()
to check the returned data, and it looks like you need to nest two of them as your result is an array that contains more arrays.Here’s an example with a mocked
axiosFunction
. Typefoo
in the input field for one result, or something else for "not found":